这个问题之前可能已经被问过,但我是python的新手,缺少更好的搜索关键词让我提出问题。
我有两个清单:
list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
couples = [x + ' and ' y for x in list1 y in list2] # I can't do that
我的情侣列表应如下所示:
['John and Melissa', 'Don and Amber', 'Sam and Liz']
如何以这种方式连接这两个列表?
提前致谢
答案 0 :(得分:4)
>>> list1 = ['John', 'Don', 'Sam']
>>> list2 = ['Melissa', 'Amber', 'Liz']
>>> [' and '.join(i) for i in zip(list1, list2)]
['John and Melissa', 'Don and Amber', 'Sam and Liz']
答案 1 :(得分:1)
您可以使用zip()
遍历两个列表:
couples = [x + ' and ' + y for x, y in zip(list1, list2)]
答案 2 :(得分:1)
zip
列出并使用str.format
list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
print ["{} and {}".format(*name) for name in zip(list1,list2)]
['John and Melissa', 'Don and Amber', 'Sam and Liz']
您还可以使用枚举:
list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
print ["{} and {}".format(name,list2[ind]) for ind, name in enumerate(list1)]
['John and Melissa', 'Don and Amber', 'Sam and Liz']