【发布时间】:2018-01-05 19:44:27
【问题描述】:
我有列表a:
a = [0,1,2,3,4,5]
然后我创建此列表的所有三元素组合。由于与二进制 3 位字符串形式的等效项匹配,因此结果被分组在 sublistach 中。比如结果[0,4,5]对应序列001,因为每个偶数对应0,奇数对应1。
我在 cmets 中使用的代码:
import itertools as it
import itertools
# I create three-element combinations of zeros and ones
combinations_3bit = list(map(list, itertools.product([0,1], repeat=3)))
# output: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
# I create a list of strings with values from the list `3bit_combinations`
a=[]
for i in range(len(combinations_3bit)):
a2 =''.join(map(str, [1 if x%2 else 0 for x in combinations_3bit[i]]))
a.append(a2)
# output: ['000', '001', '010', '011', '100', '101', '110', '111']
# I remove repetitions in pairs of type 001 with 100, 011 with 110, etc.
combinations_3bit_without_repetition = [v for k, v in enumerate(a) if v[::-1] not in a[:k]]
# output: ['000', '001', '010', '011', '101', '111']
b = [0,1,2,3,4,5]
good = []
for i in range(len(combinations_3bit_without_repetition)):
c=[]
for u in it.combinations(b, 3):
u1 = list(u)
y =''.join(map(str, [1 if x%2 else 0 for x in u1]))
if y == combinations_3bit_without_repetition[i]:
c.append(u1)
good.append(c)
# output: [[[0, 2, 4]], [[0, 2, 3], [0, 2, 5], [0, 4, 5], [2, 4, 5]], [[0, 1, 2], [0, 1, 4], [0, 3, 4], [2, 3, 4]], [[0, 1, 3], [0, 1, 5], [0, 3, 5], [2, 3, 5]], [[1, 2, 3], [1, 2, 5], [1, 4, 5], [3, 4, 5]], [[1, 3, 5]]]
能否更好、更经济地解决这个问题?
因为上面的解决方案似乎是“围绕”的,例如函数it.combinations 在列表combinations_3bit_without_repetition 中的每个索引i 之后返回所有可能的组合,只有这样,条件才会筛选匹配的组合。在大列表的情况下,这个解决方案很弱;)
【问题讨论】:
标签: python python-3.x list combinations itertools