动态创建python中的x列表

时间:2010-08-12 21:07:39

标签: python list

(首先,我选择在Python中执行此操作,因为我从未在其中编程,这将是一个很好的做法。)

有人要我实施一个小的“组合”程序,基本上输出一组数字组的所有可能组合。例如,如果你有:
(1,2,3)作为第一组,
(4,5,6)为第二,和 (7,8,9)作为第三个,然后一个组合将是(1,4,7),依此类推,共有27种可能的组合。 这个人只想做一个6rows x 6cols矩阵或5rows x 6cols矩阵。但是,我想让我的小程序尽可能灵活。
下一个要求是仅输出具有X偶数的组合。如果他想要0偶数,那么可能的组合将是(1,5,7)。你明白了。 对于排列部分,我使用了itertools.product(),它完美地运行。 如果我假设每组(cols)中的数字数固定为6,那将很容易。 在这种情况下,我可以手动创建6个列表,并将每个组合附加到右侧列表中。 然而,我希望这可以使用N个cols。

我正在考虑两种方法可以做到这一点,但尝试没有运气。 所以我的问题是: 我该如何创建?

li_1 = [] 
li_2 = [] 
...
li_x = [] 

我尝试使用“列表列表”的一种方式:

for combination in itertools.product(*li):
    total_combinations = total_combinations + 1
    #Counts number of even numbers in a single combination
    for x in range(numberInRows):
        if combination[x] % 2 == 0:
            even_counter = even_counter + 1
    print "Even counter:",even_counter
    num_evens[even_counter].append(combination)
    print "Single set:",num_evens
    even_counter = 0

    print combination
print "Num_evens:",num_evens

print '\nTotal combinations:', total_combinations

3 个答案:

答案 0 :(得分:1)

Ls = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
import collections
import itertools

def products_by_even_count(seq):
    ret = collections.defaultdict(set)
    for p in itertools.product(*seq):
        n_even = sum(1 for n in p if n % 2 == 0)
        ret[n_even].add(p)
    return ret

import pprint
# Calling dict() is only necessary for pretty pprint output.
pprint.pprint(dict(products_by_even_count(Ls)))

输出:

{0: set([(1, 5, 7), (1, 5, 9), (3, 5, 7), (3, 5, 9)]),
 1: set([(1, 4, 7),
         (1, 4, 9),
         (1, 5, 8),
         (1, 6, 7),
         (1, 6, 9),
         (2, 5, 7),
         (2, 5, 9),
         (3, 4, 7),
         (3, 4, 9),
         (3, 5, 8),
         (3, 6, 7),
         (3, 6, 9)]),
 2: set([(1, 4, 8),
         (1, 6, 8),
         (2, 4, 7),
         (2, 4, 9),
         (2, 5, 8),
         (2, 6, 7),
         (2, 6, 9),
         (3, 4, 8),
         (3, 6, 8)]),
 3: set([(2, 4, 8), (2, 6, 8)])}

答案 1 :(得分:1)

num_evens = {} 
for combination in itertools.product(*li):
    even_counter = len([ y for y in combination if y & 1 == 0 ])
    num_evens.setdefault(even_counter,[]).append(combination)

import pprint
pprint.pprint(num_evens)

答案 2 :(得分:1)

from itertools import product
from collections import defaultdict
num_evens = defaultdict(list)
for comb in product(*li):
    num_evens[sum(y%2==0 for y in comb)].append(comb)

import pprint
pprint.pprint(num_evens)