将嵌套列表简化为笛卡尔积

时间:2016-06-03 12:41:22

标签: python recursion nested-lists

我在Python中有一个嵌套列表:

lst = ['alpha', ['beta', 'gamma'], ['delta', 'peta', 'lambda']]

我需要一个能够返回具有笛卡尔积的列表的函数。好吧,我认为笛卡尔积不是一个正确的词,但仍然以合乎逻辑的方式结果如下:

final_lst = your_magical_function(lst)
print final_lst

'''
[['alpha','beta','delta'],
['alpha','beta','peta'],
['alpha','beta','lambda'],
['alpha','gamma','delta'],
['alpha','gamma','peta']
['alpha','gamma','lambda']]
'''

一个递归或不递归的函数,欢迎两者。

3 个答案:

答案 0 :(得分:1)

使用itertools.product,这需要您稍微修改输入(Interval'alpha'):

['alpha']

答案 1 :(得分:1)

将所有项目转换为列表后,您可以使用itertools.product

loadURL()

答案 2 :(得分:1)

在Python中使用库非常棒!但是,如果您正在寻找纯Python实现:

def CartesianProduct(list_entry):
# Save Sizes of Everything
size_dictionary = {}

# Get Size of Entire Entry List
size_dictionary["full_size"] = len(list_entry)

# Get Sizes of All Sub Entries
for i in range(len(list_entry)):
    if not (isinstance(list_entry[i],list)):
        list_entry[i] = [list_entry[i]]
    size_dictionary[i] = len(list_entry[i])

# Now lets create the cartesian product
# Lets Create a Dictionary to hold all of the results
cartesian_result = {}

# Lets get the size of the final result
final_result_amount = 1
for i in range(size_dictionary["full_size"]):
    final_result_amount = final_result_amount * size_dictionary[i]

# And create the final results
for i in range(final_result_amount):
    cartesian_result[i] = []

    for j in range(size_dictionary["full_size"]):
        cartesian_result[i].append(list_entry[j][i % size_dictionary[j]])

    print(cartesian_result[i])

def main():
    lst = ['alpha',['beta','gamma'],['delta','peta','lambda']]
    CartesianProduct(lst)

main()

它不像使用itertools那么漂亮和简单,但是实现库偶尔使用的逻辑很有趣。