For the following 2 input lists, I want different output lists based on the first one:
al = ["tr1", "tr2", "tr3"]
bl = ["tile1", "tile2", "tile3"]
newlist = []
for a in al:
for b in bl:
c = a+b+"5"
newlist.append(c)
print(newlist)
['tr1tile15', 'tr1tile25', 'tr1tile35', 'tr2tile15', 'tr2tile25', 'tr2tile35', 'tr3tile15', 'tr3tile25', 'tr3tile35']
Desired output:
newlist_tr1 = ['tr1tile15', 'tr1tile25', 'tr1tile35']
newlist_tr2 = ['tr2tile15', 'tr2tile25', 'tr2tile35']
newlist_tr3 = ['tr3tile15', 'tr3tile25', 'tr3tile35']
Working on Windows 10, Python 3.7.6.
You need an intermediate list in the loop
al = ["tr1", "tr2", "tr3"]
bl = ["tile1", "tile2", "tile3"]
newlist = []
for a in al:
tmp = []
for b in bl:
tmp.append(a + b + "5")
newlist.append(tmp)
print(newlist)
# [['tr1tile15', 'tr1tile25', 'tr1tile35'],
['tr2tile15', 'tr2tile25', 'tr2tile35'],
['tr3tile15', 'tr3tile25', 'tr3tile35']]
You can achieve the same with lists-comprehension
newlist = [[a + b + "5" for b in bl] for a in al]
al = ["tr1", "tr2", "tr3"]
bl = ["tile1", "tile2", "tile3"]
newlist = [[a + b + "5" for b in bl] for a in al]
Result:
[['tr1tile15', 'tr1tile25', 'tr1tile35'],
['tr2tile15', 'tr2tile25', 'tr2tile35'],
['tr3tile15', 'tr3tile25', 'tr3tile35']]
bl = ["tile1", "tile2", "tile3"]
newlist = []
for a in al:
for b in bl:
c = a+b+"5"
newlist.append(c)
print(newlist)
newlist = []
['tr1tile15', 'tr1tile25', 'tr1tile35']
['tr2tile15', 'tr2tile25', 'tr2tile35']
['tr3tile15', 'tr3tile25', 'tr3tile35']```
from itertools import product
m=["".join(elem)+'5' for elem in list(product(al,bl))]
for i in al:
newlist_i =m[:len(al)]
product(A, B) returns the same as ((x,y) for x in A for y in B)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.