如何将列表的每个元素组合到另一个列表中

时间:2017-03-07 03:54:21

标签: python loops

假设有两个列表:

['a', 'b', 'c'], ['d', 'e', 'f']

我想要的是:

'ad','ae','af','bd','be','bf','cd','ce','cf'


 first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
    for j in second_list:
        combined_list.append(i + j)
print(combined_list)

我的问题是,如果不仅有两个列表,如何改进代码? 例如,

first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
print ['adg','adh','adq','aeg','aeh',.......]

伙计们,是否有任何可推广的方式来显示n个列表..我的意思是如果有超过三个列表?

2 个答案:

答案 0 :(得分:2)

这被称为笛卡尔积。

import itertools

first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
lists = [first_list, second_list, third_list]

cartesian_product = [''.join(x) for x in itertools.product(*lists)]

print(cartesian_product)

输出:

['adg', 'adh', 'adq', 'aeg', 'aeh', 'aeq', 'afg', 'afh', 'afq',
 'bdg', 'bdh', 'bdq', 'beg', 'beh', 'beq', 'bfg', 'bfh', 'bfq',
 'cdg', 'cdh', 'cdq', 'ceg', 'ceh', 'ceq', 'cfg', 'cfh', 'cfq']

您可以在线试用here

以下是笛卡尔生产函数的示例实现,您可以尝试here

def cartesian_product(*lists):
    if not lists: # base case
        return [[]]
    else:
        this_list = lists[0]
        remaining_lists = lists[1:]
        return [
          [x] + p
            for x in this_list
              for p in cartesian_product(*remaining_lists)
        ]

答案 1 :(得分:0)

我还没有对此进行测试,但这应该可行。

first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
combined_list = []
for i in first_list:
    for j in second_list:
        for k in third_list:
            combined_list.append(i + j + k)
print(combined_list)