【发布时间】:2020-09-18 16:37:58
【问题描述】:
我需要减少执行生成一些组合列表的 python 脚本的时间。问题简单说明:
有两个列表:
char_list = ['a','b','c','d','e','f','g','h']
n_list = [3,2,1,2]
目标是根据n_list 中的模式创建一个包含char_list 中所有可能的字符组合的集合(列表、元组或任何你想要的),长度和顺序根据模式。 1680 个可能的例子:
(('a', 'd', 'e'), ('h', 'c'), ('b',), ('d', 'f'))
集合中的所有组合都必须像上面的这个,唯一会改变的是特定字符的位置。这就是困难开始的地方,因为有些规则不能省略:
- 每个组合中不能有重复的字符(每个 字符只能组合出现一次)
- 在相同的元组中更改了字符顺序的组合 以前的位置也被视为重复项(此规则 更复杂,所以让我举个例子):
假设我们的收藏中有数千种组合,突然间我们注意到四个看起来几乎相同:
(('a', 'c', 'e'), ('b', 'd'), ('g',), ('f', 'h'))
(('a', 'c', 'e'), ('h', 'f'), ('g',), ('d', 'b'))
(('a', 'c', 'e'), ('f', 'h'), ('g',), ('b', 'd'))
(('a', 'e', 'c'), ('h', 'f'), ('g',), ('d', 'b'))
其中只有两个是正确的(可以属于我们的集合,顺便说一句,这种情况意味着整个集合都是错误的,因为这四个组合中有两个是错误的)哪一个?第一个很好(至少对于这个例子来说),但是在接下来的三个的情况下,只有一个很好,这是第一个(这三个中的第一个,如果我们从所有 4 个的开头算起,第二个组合),因为它出现在整个集合中的下两个之前。为什么第三和第四组合不是唯一的?因为其中具有特定字符顺序的元组的位置没有改变;只有字符交换了位置,但只有特定的元组,这并不是使整个组合独一无二的原因。再次查看第一个和第三个组合的元组。他们是一样的。但是这些元组的顺序是不同的。第一个的一个(顺序)相对于其他是唯一的。 我解决这个编码问题的方法:
import itertools as iter
char_list = ['a','b','c','d','e','f','g','h']
n_list = [3,2,1,2]
###this line creates a list of all possible combinations of characters within tuples###
char_comb_in_tuples = list(iter.chain(*[list(iter.combinations(char_list,n)) for n in n_list]))
### this is list in which the appropriate combinations will be appended###
list_of_good_combinations = []
###for loop for looping over all possible combinations of tuples from 'char_comb_in_tuples'###
for combination in iter.combinations(char_comb_in_tuples,4):
###filtering only these combinations with appropriate pattern from n_list (3,2,1,2)###
if len([tuple for n_list_number, tuple in zip(n_list, combination) if n_list_number ==len(tuple)])==4:
###filtering only these combinations with no character duplicates###
if len(list(iter.chain(*combination))) != len(set(list(iter.chain(*combination)))):
pass
else:
###appending right combination to final list###
list_of_good_combinations.append(combination)
else:
pass
【问题讨论】:
标签: python python-3.x combinations