2016-07-13 51 views
0

未知數量的不同尺寸的列表中的所有可能的組合中的所有值我想實現一個垂直結合所有的數目不詳的Python列表的元素的功能。每個列表有不同的大小。 例如,這是列表的列表,每一行是一個列表:垂直閱讀在Python

A0, A1 
B0 
C0, C1, C2 

然後我想打印

A0, B0, C0 
A0, B0, C1 
A0, B0, C2 
A1, B0, C0 
A1, B0, C1 
A1, B0, C2 

注意,在本例中有3個表,但它們也可以更或更少,沒有必要3. 我的問題是,我不知道如何解決它。我很難實現遞歸方法,其中如果滿足某些條件,則打印該值,否則遞歸調用該函數。這裏的僞代碼:

def printVertically(my_list_of_list, level, index): 
    if SOME_CONDITION: 
     print str(my_list_of_list[index]) 

    else: 
     for i in range (0, int(len(my_list_of_list[index]))): 
      printVertically(my_list_of_list, level-1, index) 

這裏主要代碼:

list_zero = [] 
list_zero.append("A0") 
list_zero.append("B0") 
list_zero.append("C0") 

list_one = [] 
list_one.append("A1") 

list_two = [] 
list_two.append("A2") 
list_two.append("B2") 

list_three = [] 
list_three.append("A3") 
list_three.append("B3") 
list_three.append("C3") 
list_three.append("D3") 


my_list_of_list = [] 
my_list_of_list.append(list_zero) 
my_list_of_list.append(list_one) 
my_list_of_list.append(list_two) 
my_list_of_list.append(list_three) 


level=int(len(my_list_of_list)) 
index=0 
printVertically(my_list_of_list, level, index) 

水平是列表和索引的列表的長度應代表當用於特定列表的索引我想打印一個特定的元素。那麼,不知道如何繼續。任何提示?

我已經搜查,但在所有的解決方案,人們知道列表的數量或每個列表中元素的個數,這樣的鏈接:

Link 1

Link 2

Link 3

+0

請解釋一下你怎麼從你輸入到你所需的輸出;也許一個完整的例子(沒有橢圓!)會有所幫助。 –

+0

@ScottHunter我改進了它 –

+0

你能告訴我應該如何使用'index',以及預期輸出的非零示例嗎?謝謝。 – cdarke

回答

2

我相信你在這裏想要的是各種組合的交叉產品。你可以用Python的itertools.product方法做到這一點。文檔是here。喜歡的東西:

import itertools 
a_list = ["A0", "A1"] 
b_list = ["B0"] 
c_list = ["C0", "C1", "C2"] 
for combo in itertools.product(a_list, b_list, c_list): 
    print combo 

輸出:

('A0', 'B0', 'C0') 
('A0', 'B0', 'C1') 
('A0', 'B0', 'C2') 
('A1', 'B0', 'C0') 
('A1', 'B0', 'C1') 
('A1', 'B0', 'C2') 

這是否讓你感動?


例一個總體列表:

my_list_list = [a_list, b_list, c_list] 
for combo in itertools.product(*my_list_list): 
    print combo 

...我們得到的結果相同

+0

我正在測試這段代碼,但我不知道應該用什麼來代替'...'來打印所有的組合..任何提示?謝謝。 –

+0

沒問題 - 請參閱上面的編輯。 – Prune

+0

正是我需要的!謝謝:) –