簡體   English   中英

垂直讀取Python中不同大小的未知數量列表的所有可能組合的所有值

[英]Read vertically all the values of all the possible combinations of an unknown number of lists with different sizes in 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)

級別是列表列表的長度, 索引應代表我要打印特定元素時使用的特定列表的索引。 好吧,不知道如何進行。 有什么提示嗎?

我進行了搜索,但是在所有解決方案中,人們都知道列表的數量或每個列表中的元素數量,例如以下鏈接:

鏈接1

連結2

連結3

我相信您想要的是各種組合的叉積。 您可以使用Python的itertools.product方法執行此操作。 文檔在這里 就像是:

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

...我們得到相同的輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM