Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两个列表合并为具有自定义条件的元组列表_Python_List_Python 2.7_Itertools_Cartesian Product - Fatal编程技术网

Python 将两个列表合并为具有自定义条件的元组列表

Python 将两个列表合并为具有自定义条件的元组列表,python,list,python-2.7,itertools,cartesian-product,Python,List,Python 2.7,Itertools,Cartesian Product,我是python新手,对python中的快捷方式知之甚少。 我有两份清单: firstList = ['a','b','c'] and secondList = [1,2,3,4] 我必须通过合并这些列表来创建一个元组列表,这样输出应该是这样的 [('a',1),('a',2),('a',3),('a',4),('b',1), ('b',2) .....] 一个简单的方法是 outputList = [] for i in firstList: for j in secondLi

我是python新手,对python中的快捷方式知之甚少。 我有两份清单:

firstList = ['a','b','c']  and
secondList = [1,2,3,4]
我必须通过合并这些列表来创建一个元组列表,这样输出应该是这样的

[('a',1),('a',2),('a',3),('a',4),('b',1), ('b',2) .....]
一个简单的方法是

outputList = [] 
for i in firstList:
    for j in secondList:
        outputList.append((i,j))
这两个
for
循环让我头疼。有没有更好的方法(复杂性更低)或python中的内置函数来做到这一点??你的帮助将不胜感激

>>> firstList = ['a','b','c']
>>> secondList = [1,2,3,4]
>>> from itertools import product
>>> list(product(firstList, secondList))
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('b', 1), ('b', 2), ('b', 3), ('b', 4), ('c', 1), ('c', 2), ('c', 3), ('c', 4)]
这里还有一个更好的for循环版本,使用列表理解:

>>> [(i, j) for i in firstList for j in secondList]
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('b', 1), ('b', 2), ('b', 3), ('b', 4), ('c', 1), ('c', 2), ('c', 3), ('c', 4)]

你的问题标题中的“自定义条件”是什么?@Inbar Rose:我很抱歉……它应该是“给定”而不是“自定义”。那么,给定的条件是什么呢?很好的答案,+1.)我会如何回答(列表理解部分)这就是我想要的…谢谢!在这两个列表中,哪一个会执行得更快?@user1863122我总是选择
产品
,对于大型列表来说应该快一吨,但是对于较小的列表来说,差异可以忽略不计。@jamylak:再次感谢:)