在Python中动态创建x个列表
(首先,我选择用Python来做这个,因为我从来没有用过这个语言,练习一下也不错。)
有人让我写一个小程序,主要是输出一组数字的所有可能组合。比如说,如果你有:
第一组是(1,2,3),
第二组是(4,5,6),
第三组是(7,8,9),那么其中一个组合就是(1,4,7),依此类推,总共有27种可能的组合。
这个人只想做一个6行x 6列的矩阵或者一个5行x 6列的矩阵。不过,我想让我的小程序尽可能灵活。
下一个要求是只输出包含X个偶数的组合。如果他想要0个偶数,那么一个可能的组合就是(1,5,7)。你明白我的意思了吧。
在排列组合的部分,我用了itertools.product(),效果很好。
如果我假设每组中的数字数量(列数)是固定的6,那就简单多了。
在这种情况下,我可以手动创建6个列表,把每个组合添加到正确的列表中。
但是,我还是想让这个程序适用于任意数量的列。
我在想我可能有两种方法可以做到这一点,但尝试了都没有成功。
所以我的问题是:
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 个回答
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)
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
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)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。