簡體   English   中英

Python:從附加到單個列表的三個單獨列表中獲取唯一組合?

[英]Python : Get unique combinations from three seperate lists appended to a single list?

我有三個包含值的列表,

        first_lst = ['a','b','c','d']
        second_lst = ['i','j','k']
        third_lst = ['x','y']

我正在嘗試將所有三個列表 append 的唯一組合添加到一個列表中。

結果 Output:

  output = [['a','j','y'],['d','k','x'],............['d','k','y']]

標准庫中的itertools.product是這樣做的:

import itertools
output = [list(item) for item in itertools.product(first_lst, second_lst, third_lst)]

好的,如果我理解正確的話,您希望列表變成列表之間所有組合的列表,如下所示: [1, 2][3, 4]變成[[1, 3], [1, 4], [2, 3], [2, 4]]

執行此操作的一種方法只是一個循環的循環:

first_lst = ['a', 'b', 'c', 'd']
second_lst = ['i', 'j', 'k']
third_lst = ['x', 'y']
new_lst = []

for x in first_lst:
    for y in second_lst:
        for z in third_lst:

            new_lst.append([x, y, z])

print(new_lst)

印刷:

[['a', 'i', 'x'], ['a', 'i', 'y'], ['a', 'j', 'x'], ['a', 'j', 'y'], ['a', 'k', 'x'], ['a', 'k', 'y'], ['b', 'i', 'x'], ['b', 'i', 'y'], ['b', 'j', 'x'], ['b', 'j', 'y'], ['b', 'k', 'x'], ['b', 'k', 'y'], ['c', 'i', 'x'], ['c', 'i', 'y'], ['c', 'j', 'x'], ['c', 'j', 'y'], ['c', 'k', 'x'], ['c', 'k', 'y'], ['d', 'i', 'x'], ['d', 'i', 'y'], ['d', 'j', 'x'], ['d', 'j', 'y'], ['d', 'k', 'x'], ['d', 'k', 'y']]

使用zip() function 迭代多個可迭代項,如 python 中的列表、元組、字典。

first_lst = ['a', 'b', 'c', 'd']
second_lst = ['i', 'j', 'k']
third_lst = ['x', 'y']
output = []
for f, s, t in zip(first_lst, second_lst, third_lst):
    output.append([f, s, t])
print(output)

暫無
暫無

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

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