逐个组合多个列表

时间:2014-01-07 23:53:35

标签: python

我有3个列表,我想将我的三个列表组合到另一个列表中,其中包含元组或列表,这三个列表混合在一起,如下所示:

years = [2012,2013,2011,2014,2015]
sessions = ["AC", "AB"]
periods = ["I", "II", "III"]

我想知道是否有一个函数或者什么是 Pythonic 的方式来完成下一个:

result = function(years,sessions,periods)
print result 

##  [(2012, "AC", "I"), (2012, "AC", "II"), (2012, "AC", "III"), (2012, "AB", "I")] and so on

1 个答案:

答案 0 :(得分:5)

您可以使用itertools.product()

>>> years = [2012,2013,2011,2014,2015]
>>> sessions = ["AC", "AB"]
>>> periods = ["I", "II", "III"]
>>> 
>>> from itertools import product
>>> 
>>> list(product(years, sessions, periods))
[(2012, 'AC', 'I'), (2012, 'AC', 'II'), (2012, 'AC', 'III'), (2012, 'AB', 'I'), (2012, 'AB', 'II'), (2012, 'AB', 'III'), (2013, 'AC', 'I'), (2013, 'AC', 'II'), (2013, 'AC', 'III'), (2013, 'AB', 'I'), (2013, 'AB', 'II'), (2013, 'AB', 'III'), (2011, 'AC', 'I'), (2011, 'AC', 'II'), (2011, 'AC', 'III'), (2011, 'AB', 'I'), (2011, 'AB', 'II'), (2011, 'AB', 'III'), (2014, 'AC', 'I'), (2014, 'AC', 'II'), (2014, 'AC', 'III'), (2014, 'AB', 'I'), (2014, 'AB', 'II'), (2014, 'AB', 'III'), (2015, 'AC', 'I'), (2015, 'AC', 'II'), (2015, 'AC', 'III'), (2015, 'AB', 'I'), (2015, 'AB', 'II'), (2015, 'AB', 'III')]

注意product()返回一个可迭代的;我刚刚将它转换为上面的列表以用于演示目的,但除非您确实需要列表,否则不应该这样做。