Index of \n in Python list - python

Okay, here I have another problem, I need to find position of \n alone in my list.
list = ['abc', '\n', 'def', 'ghi', '\n', 'jkl']
So, I need to get the position of all '\n' entries from this list.
I used
a=list.index('\n')
but got only one value as '1'. How to get both positions?
e.g. I will get a list with the position of '\n'
position = ['1', '4']
'1' represents first position of \n in list and the '4' represents second at the fourth place in list.

You'll need to iterate over the elements. This can be easily done by using a list comprehension and enumerate for the indexes:
indexes = [i for i, val in enumerate(list) if val == '\n']
Demo:
>>> lst = ['abc', '\n', 'def', 'ghi', '\n', 'jkl']
>>> [i for i, val in enumerate(lst) if val == '\n']
[1, 4]

[i for i, x in enumerate(l) if x == "\n"]
# => [1, 4]
And don't call a list list since this is a builtin function.

To find indices of an item in a list with multiple occurrences, following code should work
print [i for i in range(len(list)) if list[i] == '\n']
Here I have used list as it was taken in your question but do not use keywords as variables .

Related

Removing specific set of characters in a list of strings

I have a list of strings, and want to use another list of strings and remove any instance of the combination of bad list in my list. Such as the output of the below would be foo, bar, foobar, foofoo... Currently I have tried a few things for example below
mylist = ['foo!', 'bar\\n', 'foobar!!??!!', 'foofoo::!*']
remove_list = ['\\n', '!', '*', '?', ':']
for remove in remove_list:
for strings in mylist:
strings = strings.replace(bad, ' ')
The above code doesnt work, I did at one point set it to a new variable and append that afterwords but that wasnt working well becuase if their was two issues in a string it would be appended twice.
You changed the temporary variable, not the original list. Instead, assign the result back into mylist
for bad in remove_list:
for pos, string in enumerate(mylist):
mylist[pos] = string.replace(bad, ' ')
Try this:
mylist = ['foo!', 'bar\\n', 'foobar!!??!!', 'foofoo::!*']
bads = ['\\n', '!', '*', '?', ':']
result = []
for s in mylist:
# s is a temporary copy
for bad in bads:
s = s.replace(bad, '') # for all bad remove it
result.append(s)
print(result)
Could be implemented more concise, but this way it's more understandable.
I had a hard time interpreting the question, but I see you have the result desired at the top of your question.
mylist = ['foo!', 'bar\\n', 'foobar!!??!!', 'foofoo::!*']
remove_list = ['\\n', '!', '*', '?', ':']
output = output[]
for strings in mylist:
for remove in remove_list:
strings = strings.replace(remove, '')
output.append(strings)
import re
for list1 in mylist:
t = regex.sub('', list1)
print(t)
If you just want to get rid of non-chars do this. It works a lot better than comparing two separate array lists.
Why not have regex do the work for you? No nested loops this way (just make sure to escape correctly):
import re
mylist = ['foo!', 'bar\\n', 'foobar!!??!!', 'foofoo::!*']
remove_list = [r'\\n', '\!', '\*', '\?', ':']
removals = re.compile('|'.join(remove_list))
print([removals.sub('', s) for s in mylist])
['foo', 'bar', 'foobar', 'foofoo']
Another solution you can use is a comprehension list and remove the characters you want. After that, you delete duplicates.
list_good = [word.replace(bad, '') for word in mylist for bad in remove_list]
list_good = list(set(list_good))
my_list = ["foo!", "bar\\n", "foobar!!??!!", "foofoo::*!"]
to_remove = ["!", "\\n", "?", ":", "*"]
for index, item in enumerate(my_list):
for char in to_remove:
if char in item:
item = item.replace(char, "")
my_list[index] = item
print(my_list) # outputs [“foo”,”bar”,”foobar”,”foofoo”]

How to make a list of strings with a for loop

Assume I have a list=[1,2,3,4] then I want to make a list of strings which length of each string associated with corresponding value in a list.
It means the final output should be like this:
strs=['1', '11', '111', '1111']
I tried the code below but I am not sure how to continue.
lis=[1,2,3,4]
strs=[]
for i in range (len(lis)):
st=lis[i]
strs.append(st)
The multiplication for strings is repetition, so:
lst=[1,2,3,4]
result = []
for e in lst:
result.append('1'*e)
print(result)
Output
['1', '11', '111', '1111']
You first need to loop over the list of lengths lis
Then in each iteration looping n times (the given length of that iteration) and appending 1 each time to the newStr.
And after the iteration adding the newStr to the list strs
lis = [1,2,3,4]
strs = []
for n in lis:
newStr = ""
for x in range(n):
newStr += str('1')
strs.append(newStr)

How do I split strings from a list and store them to another list?

I am trying to split the strings from a list based on the whitespaces.
My code:
line=['abc def','ghi jk']
for x in line:
word=x.split(' ')
print(word)
Expected output:
['abc','def','ghi','jk']
But I keep getting the output as:
['ghi','jk']
Where am I going wrong?
You can join the strings with a space first before splitting the string by spaces:
' '.join(line).split()
This returns:
['abc', 'def', 'ghi', 'jk']
Every time word=x.split(' ') runs, the previous value of words is replaced by a new value. In your case, the first iteration of the loop creates word = ['abc','def'], and the second iteration replaces it by word = ['ghi','jk'].
You need to store the result of each iteration into a new list:
line = ['abc def', 'ghi jk']
result = []
for x in line:
result.extend(x.split(' '))
print(result)
A neat one-liner:
Given line = ['abc def', 'ghi jk']
word = [item for sublist in [elem.split() for elem in line] for item in sublist]
Then you have
>>> word
['abc', 'def', 'ghi', 'jk']
What happens here? The [elem.split() for elem in line] is a list-comprehension, taking elem.split() for each element in the original list line, and putting each result in a list.
>>> [elem.split() for elem in line]
[['abc', 'def'], ['ghi', 'jk']]
Suppose then, that we again use list-comprehension and take from each element of our new nested list, each element it has, and puts it in a list. The procedure is called flattening of a list, and is of the form:
flattened_list = [item for sublist in nestedlists for item in sublist]
Split it, then flatten
line = ['abc def','ghi jk']
temp = [s.split(' ') for s in line]
res = [c for s in temp for c in s]
print(res)
Result
['abc','def','ghi','jk']
Or by using operator and reduce
import operator
from functools import reduce
line = [s.split(' ') for s in line]
res = reduce(operator.concat, line)
print(res)
Result:
['abc', 'def', 'ghi', 'jk']

Convert certain values in list to int

I have a list of lists and I want to convert the second value in each list to an int since it is currently a string
[['hello','how','are','you','1'],['hello','how','are','you','2']]
I am trying to convert index 4 to an int in each list within this larger list but when I do
for hi in above:
int(hi[4])
It is just returning the int when I print the list and not the entire list.
Just traverse it and convert it using the int() function for every 4th element in every list inside :
for li in my_list:
li[4] = int(li[4])
This list comprehension is one way to do it:
a_list = [[int(a) if item.index(a) == 4 else a for a in item] for item in a_list]
Demo:
>>> a_list = [['hello','how','are','you','1'],['hello','how','are','you','2']]
>>> a_list = [[int(a) if item.index(a) == 4 else a for a in item] for item in a_list]
>>> a_list
[['hello', 'how', 'are', 'you', 1], ['hello', 'how', 'are', 'you', 2]]
>>>

Python: Inline if to print non-empty strings?

I'm trying to print out just the non-empty strings in a list. I can't seem to get the below to work, what am I doing wrong??
print item in mylist if item is not ""
The following is invalid syntax: print item in mylist if item is not ""
You could perhaps achieve what you want using a list comprehension:
>>> mylist = ["foo","bar","","baz"]
>>> print [item for item in mylist if item]
['foo', 'bar', 'baz']
You could create a generator to grab the items in the list that are not empty.
nonempties = (item for item in mylist if item)
Then loop and print or join them into a string.
print ' '.join(nonempties)
The filter() built-in is well suited for exactly that, just pass None instead of a function:
>>> filter(None, ['Abc', '', 'def', None, 'ghi', False, 'jkl'])
['Abc', 'def', 'ghi', 'jkl']
Details at http://docs.python.org/library/functions.html

Categories