Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 在Python中,每个列表使用一个项来生成组合(按特定顺序)?_Python 2.7_Dictionary_Combinations_Combinatorics - Fatal编程技术网

Python 2.7 在Python中,每个列表使用一个项来生成组合(按特定顺序)?

Python 2.7 在Python中,每个列表使用一个项来生成组合(按特定顺序)?,python-2.7,dictionary,combinations,combinatorics,Python 2.7,Dictionary,Combinations,Combinatorics,我有一个相当复杂的问题(至少在我看来是这样)。我有一本字典,上面有元素的键列表和该字典的键列表 numbers = { 'group1': [1, 2], 'group2': [3, 4], 'group3': [5, 6] } order = [ 'group1', 'group2', 'group3' ] 我想按照给定的顺序,使用每组一个数字来生成组合。因此,按照顺序['group1'、'gr

我有一个相当复杂的问题(至少在我看来是这样)。我有一本字典,上面有元素的键列表和该字典的键列表

numbers = { 
            'group1': [1, 2],
            'group2': [3, 4],
            'group3': [5, 6]
          }
order   = [ 'group1', 'group2', 'group3' ]
我想按照给定的顺序,使用每组一个数字来生成组合。因此,按照顺序
['group1'、'group2'、'group3']
我希望

1, 3, 5
1, 3, 6
1, 4, 5
1, 4, 6
2, 3, 5
2, 3, 6
2, 4, 5
2, 4, 6
我有一个解决方案,但它不够通用,无法扩展:

group1=order[0]
group2=order[1]
group3=order[2]
for n in numbers[group1]:
    for n2 in numbers[group2]:
        for n3 in numbers[group3]:
            print(n, n2, n3)

任何适用于任意数量组的智能解决方案?

您可以使用、和元组解包的组合:

import itertools

for ns in itertools.product(*[numbers[g] for g in order]):
    print(*ns) # or 'print ns' for 2.x
这给了我你想要的结果:

1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6

这些星号是用来干什么的?值得注意的是,
print(*ns)
不适用于python2.x。使用
print(ns)
。如果您使用的是Python 2.x,
print
是一个语句,而不是一个函数-使用
print ns
。另外,请用适当的版本标记您的问题。