Related
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)
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I want to remove all elements in a list which contains (or does not contain) a set of specific characters, however I'm running in to problems iterating over the list and removing elements as I go along. Two pretty much equal examples of this is given below. As you can see, if two elements which should be removed are directly following each other, the second one does not get removed.
Im sure there are a very easy way to do this in python, so if anyone know it, please help me out - I am currently making a copy of the entire list and iterating over one, and removing elements in the other...Not a good solution I assume
>>> l
['1', '32', '523', '336']
>>> for t in l:
... for c in t:
... if c == '2':
... l.remove(t)
... break
...
>>> l
['1', '523', '336']
>>> l = ['1','32','523','336','13525']
>>> for w in l:
... if '2' in w: l.remove(w)
...
>>> l
['1', '523', '336']
Figured it out:
>>> l = ['1','32','523','336','13525']
>>> [x for x in l if not '2' in x]
['1', '336']
Would still like to know if there is any way to set the iteration back one set when using for x in l though.
List comprehensions:
l = ['1', '32', '523', '336']
[ x for x in l if "2" not in x ]
# Returns: ['1', '336']
[ x for x in l if "2" in x ]
# Returns: ['32', '523']
l = ['1', '32', '523', '336']
stringVal = "2"
print(f"{[ x for x in l if stringVal not in x ]}")
# Returns: ['1', '336']
print(f"{[ x for x in l if stringVal in x ]}")
# Returns: ['32', '523']
If I understand you correctly,
Example:
l = ['1', '32', '523', '336']
[x for x in l if "2" not in x]
# Returns: ['1', '336']
fString Example:
l = ['1', '32', '523', '336']
stringVal = "2"
print(f"{[x for x in l if stringVal not in x]}")
# Returns: ['1', '336']
might do the job.
In addition to #Matth, if you want to combine multiple statements you can write:
l = ['1', '32', '523', '336']
[ x for x in l if "2" not in x and "3" not in x]
# Returns: ['1']
fString Example
l = ['1', '32', '523', '336']
stringValA = "2"
stringValB = "3"
print(f"{[ x for x in l if stringValA not in x and stringValB not in x ]}")
# Returns: ['1']
Problem you could have is that you are trying to modify the sequence l same time as you loop over it in for t loop.
I have two lists in Python.
list1 = ['a','a','b','a','c','b','c','a','d','a','b']
list2 = ['1','2','21','12','1','32','11','12','21','3','31']
I have to group the similar elements in list1. The corresponding elements in list2 should also get grouped based on this. Output should be this:
list1 = [['a','a','a','a','a'],['b','b','b'],['c','c'],['d']]
list2 = [['1','2','12','12','3'],['21','32','31'],['1','11'],['21']]
What is the best way to do this?
If you do not care about the order of elements in the first list, you may use defaultdict:
In [7]: from collections import defaultdict
In [8]: from itertools import izip
In [9]: res = defaultdict(list)
In [10]: for k, v in izip(list1, list2):
....: res[k].append(v)
....:
In [11]: print(res)
defaultdict(<type 'list'>, {'a': ['1', '2', '12', '12', '3'], 'c': ['1', '11'], 'b': ['21', '32', '31'], 'd': ['21']})
In [12]: res.items()
Out[12]:
[('a', ['1', '2', '12', '12', '3']),
('c', ['1', '11']),
('b', ['21', '32', '31']),
('d', ['21'])]
This code worked for me:
groups = list(set(list1))
list1_tmp, list2_tmp = [], []
for char in groups:
list1_tmp.append([])
list2_tmp.append([])
for i in range(len(list1)):
list1_tmp[groups.index(list1[i])].append(list1[i])
list2_tmp[groups.index(list1[i])].append(list2[i])
list1 = list1_tmp
list2 = list2_tmp
The output should be valid as well for any other similar input.
This code should do it:
final_list1 = []
final_list2 = []
for distinct in sorted(list(set(list1))):
index = 0
distinct_list1 = []
distinct_list2 = []
for element in list1:
if element == distinct:
distinct_list1.append(element)
distinct_list2.append(list2[index])
index += 1
final_list1.append(distinct_list1)
final_list2.append(distinct_list2)
list1 = final_list1
list2 = final_list2
This will give you exactly the output you asked for. If you don't really care about the output, there are probably better ways as #soon proposed.
Here's a (kind of ugly) implementation that would do the trick:
list1 = ['a','a','b','a','c','b','c','a','d','a','b']
list2 = ['1','2','21','12','1','32','11','12','21','3','31']
def transform(in_list, other_list):
if len(in_list) != len(other_list):
raise ValueError("Lists must have the sema length!")
out_list = list()
out_other_list = list()
for i, c in enumerate(in_list):
for inner_list, inner_other_list in zip(out_list, out_other_list):
if c in inner_list:
inner_list.append(c)
inner_other_list.append(other_list[i])
break
else:
out_list.append([c])
out_other_list.append([other_list[i]])
return out_list, out_other_list
print transform(list1, list2)
Though I personally like soon's answer,This one successfully retrieve your desired output.
lst= sorted(zip(list1,list2),key=lambda x:x[0])
intList=[]
initial=lst[0][0]
count=0
for index,value in enumerate(lst):
if value[0]==initial:
continue
else:
intList.append(lst[count:index])
initial=value[0]
count=index
finList1=[[a for a,b in innerList] for innerList in intList]
finList2=[[b for a,b in innerList] for innerList in intList]
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
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']]