以下是我想要实现的输入和事后的示例:
a = [1,2,3,4]
b = [2,3,6,8]
c = [4,7,8,9]
d = [4,8,9,10]
我的目标是找到n个元素的所有组合,使得结果包含每个列表的一个或多个元素。
n = 3的结果示例。
res = [[1,3,8],[2,3,8],...etc.]
我到目前为止找到的唯一方法是使用比较,肯定是非常奇怪和慢。
任何帮助都会非常感激。
答案 0 :(得分:1)
for (i=0; i<arr.length-1; i++)
new_arr[] = parseInt(arr[i+1])-parseInt(arr[i])
这里有好东西。这种理解只保留满足条件的组合,>>> import itertools
>>> all_elements = {x for y in [a, b, c, d] for x in y}
>>> all_elements
{1, 2, 3, 4, 6, 7, 8, 9, 10}
>>> n = 3
# Find all n combinations of a set of the elements in all lists
>>> combos = set(itertools.combinations(all_elements, n))
>>> combos
{(3, 4, 6), (1, 4, 7), (1, 2, 8), (3, 8, 10), (2, 6, 9), (3, 6, 10), (3, 4, 7), (2, 3, 6), (1, 2, 9), (4, 6, 9), (2, 6, 8), (6, 8, 9), (1, 8, 9), (1, 2, 10), (2, 3, 7), (4, 6, 8), (7, 9, 10), (3, 6, 8), (4, 8, 10), (3, 6, 9), (1, 6, 8), (4, 6, 10), (4, 8, 9), (6, 8, 10), (2, 6, 7), (1, 7, 8), (1, 6, 9), (4, 7, 10), (6, 9, 10), (1, 6, 10), (3, 9, 10), (1, 8, 10), (2, 8, 9), (4, 7, 8), (3, 6, 7), (1, 3, 10), (4, 7, 9), (2, 7, 8), (1, 3, 9), (2, 4, 7), (3, 4, 8), (2, 7, 9), (1, 3, 8), (2, 4, 6), (2, 8, 10), (3, 4, 9), (1, 2, 3), (1, 6, 7), (2, 7, 10), (6, 7, 8), (7, 8, 9), (3, 4, 10), (6, 7, 9), (1, 2, 4), (2, 3, 4), (2, 9, 10), (7, 8, 10), (4, 9, 10), (6, 7, 10), (1, 4, 10), (2, 3, 8), (8, 9, 10), (1, 3, 7), (2, 4, 9), (1, 2, 6), (2, 3, 9), (3, 7, 9), (2, 4, 10), (1, 3, 6), (1, 7, 10), (1, 2, 7), (1, 4, 8), (2, 3, 10), (2, 4, 8), (1, 9, 10), (1, 7, 9), (3, 7, 8), (1, 4, 9), (1, 3, 4), (3, 8, 9), (1, 4, 6), (3, 7, 10), (4, 6, 7), (2, 6, 10)}
中的每个列表都包含组合中的至少一个元素:
[a, b, c, d]
检查出来:
>>> res = {com for com in combos if all(any(val in arr for val in com) for arr in [a, b, c, d])}