所以我需要将两个列表附加在一起。 List 1的每个元素都附加到List 2的每个元素。因此,最终列表将是这样的:['L1[0]L2[0]','L1[1]L2[1]','L1[2]L2[2]','L1[3]L2[3]']
。我一直遇到将for循环置于另一个for循环中的问题,但结果是让第一个循环元素重复多次。我明白这是行不通的,如果有人可以给我一个推动或某个地方来研究这类主题的信息。一如既往地感谢您的帮助!!这是我的代码:
def listCombo(aList):
myList=['hello','what','good','lol','newb']
newList=[]
for a in alist:
for n in myList:
newList.append(a+n)
return newList
示例:
List1=['florida','texas','washington','alaska']
List2=['north','south','west','east']
result= ['floridanorth','texassouth','washingtonwest','','alaskaeast']
答案 0 :(得分:2)
您需要使用zip。
[i+j for i,j in zip(l1, l2)]
示例:
>>> List1=['florida','texas','washington','alaska']
>>> List2=['north','south','west','east']
>>> [i+j for i,j in zip(List1, List2)]
['floridanorth', 'texassouth', 'washingtonwest', 'alaskaeast']
答案 1 :(得分:0)
列出对zip
的理解:
[x[0]+x[1] for x in zip(list1,list2)]
>>> [x[0]+x[1] for x in zip(['1','2','3'],['3','4','5'])]
# ['13', '24', '35']