2014-01-07 94 views
2

我有3個名單,我想我的三個列表合併成元組或列表裏面這三個名單混合,這樣另一個列表:合併多個列表逐一

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

我想知道是否有一個函數或什麼是最Python化方式接下來要做的:

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

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

回答

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()返回一個迭代;爲了演示目的,我已將它轉換爲上面的列表,但除非您確實需要列表,否則不應該這樣做。

+0

你就像一個神的男人,謝謝你這麼多!!!!!!!!! –

+2

@VictorCastilloTorres沒問題,很高興我能幫到你。如果你有時間的話,你可以瀏覽一下'itertools',因爲那裏有一些非常有用的功能。 – arshajii

+0

我會看到文檔,非常感謝你:)繼續幫助:) –