[英]Using while loops with for loop in list comprehension
l1=[1,2,3,4,5,6,7]
l2=[1, 4, 9, 16, 25, 36, 49]
l3=[]
new_list=[]
i=1
while i<8:
for num in l2:
l3.append(num*i)
i+=1
new_list.append(l3)
print(new_list)
如何將其轉換為列表理解?
new_list=[new_list.append(num*i) while(i<8) for num in l2 i+=1]
預期輸出:
new_list = [1, 8, 27, 64, 125, 216, 343]
這樣做:
l1=[1,2,3,4,5,6,7]
l2=[1, 4, 9, 16, 25, 36, 49]
new_list = [i*j for i,j in zip(l1, l2)]
print(new_list)
輸出
[1, 8, 27, 64, 125, 216, 343]
您可以使用列表理解和zip
:
[i*n for i, n in zip(range(1,8), l2)]
或者itertools.starmap
和operator.mul
:(不要忘記導入它們)
list(starmap(mul, zip(range(1,8), l2)))
兩者都會產生相同的輸出:
from itertools import groupby, starmap, product
from operator import itemgetter, mul
l1 = range(1,8)
l2=[1, 4, 9, 16, 25, 36, 49]
new_list1 = [i*n for i, n in zip(l1, l2)]
new_list2 = list(starmap(mul, zip(l1, l2)))
print(new_list1)
print(new_list2)
結果:
[1, 8, 27, 64, 125, 216, 343]
[1, 8, 27, 64, 125, 216, 343]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.