【问题标题】:Iterating through two list and appending the items together [duplicate]遍历两个列表并将项目附加在一起[重复]
【发布时间】:2015-12-04 02:59:14
【问题描述】:

所以我需要将两个列表附加在一起。 List one 的每个元素都附加到 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']

【问题讨论】:

  • 发布一个示例以及预期的输出。
  • 你听说过 zip 吗?
  • 我从未听说过 zip 或被教过这个。我会调查一下,谢谢!

标签: python string list loops for-loop


【解决方案1】:

您需要使用 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']

【讨论】:

  • 干净和pythonic,+1
  • 我喜欢,尽管对于较大的输入,还有一些其他方法可能在 CPython 上更快(通常不值得,但值得注意):map(''.join, zip(l1, l2))(在 Py3 上包装在 list()如果您不只是迭代结果一次或出于其他原因需要真正的list)。或者使用导入,from operator import concatmap(concat, l1, l2),这使得使用行更加简单。 :-)
【解决方案2】:

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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多