I have a list like
L=[[w,['0','0']],[r,['1']]]
I want to print it as
w = 00
r = 1
for getting this I tried like
for k in range(1,len(tab[0]))
print L[0][k][0],"=",(L[0][k][1])
but it prints like
w = ['0','0']
r = ['1']
can anyone help me? thanx in advance
In [5]: L=[['w',['0','0']],['r',['1']]]
In [6]: L1 = [item for item in L]
In [7]: L1
Out[7]: [['w', ['0', '0']], ['r', ['1']]]
In [8]: ['%s=%s' % (item[0], ''.join(item[1])) for item in L1]
Out[8]: ['w=00', 'r=1']
If the question is how do I convert ['0', '0'] to 00 then you may use join
for k in range(1,len(tab[0]))
print L[0][k][0],"=", ''.join((L[0][k][1]))
I don't fully understand the for loop (because I don't know what tab is) but to get string representation of a list, use join
Your list is wrong. Unless w and r are predefined variables, it should read as:
L=[['w',['0','0']],['r',['1']]]
In that case, the following will achieve the result:
for item in L:
print(item[0], ''.join(item[1]))
Just use a simple for-loop with string formatting:
L = [['w', ['0','0']], ['r',['1']]]
for item in L:
print '{} = {}'.format(item[0], ''.join(item[1]))
What ''.join() does it joins every item in the list separated by the '' (i.e nothing). So:
['0', '0'] --> '00'
Go with this..
L=[[w,['0','0']],[r,['1']]]
for item in L:
print item[0], '=', ''.join(item[1])
Ans:
w = 00
r = 1
Related
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”]
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 can I split a string to X chunks with length T, if given an array of sizes.
When X is len(array_chunks) and T is 'array_chunks[i]
array_chunks = [1,2,3]
my_string = "987654"
>> ['9', '87', "654"]
array_chunks = [1,2,3]
my_string = "987654"
result = []
ind = 0
for i in array_chunks:
result.append(my_string[ind: ind+i])
ind+=i
As per below a list comprehension is also possible. I used a solution with itertools.accumulate
from itertools import accumulate
[my_string[i: i+j] for i, j in zip(accumulate(range(len(array_chunks))), array_chunks)]
You can use list comprehension:
array_chunks = [1,2,3]
my_string = "987654"
new_string = [my_string[sum(array_chunks[:i]):a+sum(array_chunks[:i])] if i != 0 else my_string[:a] for i, a in enumerate(array_chunks)]
Output:
['9', '87', '654']
I have a list like this:
li = [1, 2, 3, 4, 5]
I want to change it into a string, get rid of the quotes, and get rid of the commas so that it looks like this:
1 2 3 4 5
I tried the following:
new_list = []
new_list.append(li)
new_string = " ".join(new_list)
print new_string
however I get the below error:
TypeError: sequence item 0: expected str instance, int found
Why does this happen and how can I fix this so that I get the output I want?
The items in the list need to be of the str type in order to join them with the given delimeter. Try this:
' '.join(map(str, your_list)) # join the resulting iterable of strings, after casting ints
This is happening because join is expecting an iterable sequence of strings, and yours contains int.
You need to convert this list to string either by using list comprehension:
>>> li
[1, 2, 3, 4, 5]
>>> new_li = [str(val) for val in li]
>>> new_li
['1', '2', '3', '4', '5']
or a regular for loop:
>>> for x in range(len(li)):
... li[x] = str(li[x])
...
>>> li
['1', '2', '3', '4', '5']
then your expression will work.
>>> result = ' '.join(li)
>>> result
'1 2 3 4 5'
The error is from attempting to join integers into a string, you could do this to turn every value into a string, then join them.
new_list = [str(x) for x in li]
new_string = " ".join(new_list)
As a one-liner:
new_string = " ".join([str(x) for x in li])
my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
I'm trying to split this list into sublists separated by \t
output = [['1','Melkor','Morgoth','SauronAtDolGoldul'],['2','Thigols','HeirIsDior','Silmaril'],['3','Arkenstone','IsProbablyA','Silmaril']]
I was thinking something on the lines of
output = []
for k_string in my_list:
temp = []
for i in k_string:
temp_s = ''
if i != '\':
temp_s = temp_s + i
elif i == '\':
break
temp.append(temp_s)
it gets messed up with the t . . i'm not sure how else I would go about doing it. I've seen people use .join for similar things but I don't really understand how to use .join
You want to use str.split(); a list comprehension lets you apply this to all elements in one line:
output = [sub.split('\t') for sub in my_list]
There is no literal \ in the string; the \t is an escape code that signifies the tab character.
Demo:
>>> my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
>>> [sub.split('\t') for sub in my_list]
[['1', 'Melkor', 'Morgoth', 'SauronAtDolGoldul'], ['2', 'Thingols', 'HeirIsDior', 'Silmaril'], ['3', 'Arkenstone', 'IsProbablyA', 'Silmaril']]
>>> import csv
>>> my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
>>> list(csv.reader(my_list, delimiter='\t'))
[['1', 'Melkor', 'Morgoth', 'SauronAtDolGoldul'], ['2', 'Thingols', 'HeirIsDior', 'Silmaril'], ['3', 'Arkenstone', 'IsProbablyA', 'Silmaril']]