0

I've been searching around, but I'm not quite sure how to word this. I have a list of lists, and each inner list is a certain size, k. I want to generate a list of combinations that have the size k+1. So for instance, if I start with:

[[1,2],[1,3],[3,4]]

I want to generate the list:

[[1,2,3],[1,3,4]]

Where the lists are arbitrarily long. I'm thinking I'll need to use the combinations function from the itertools library, and possibly sets with unions. I'm just kind of stuck as to how to go about this efficiently.

Any help is greatly appreciated!

Edit: I need to clarify. I'm only trying to generate the lists of length k+1 (3 in this case) where two of the original lists are combined. So if they were sets, I want only the resulting sets of length k+1 when we take the union of two sets.

4

3 回答 3

1

我不太确定您的预期输出,因为它缺少一些组合,但试试这个:

import itertools
L = [[1,2],[1,3],[3,4]]
print list(itertools.combinations(list(set(itertools.chain.from_iterable(L))), len(L[0])+1))

list(set(itertools.chain.from_iterable(L)))将展平列表并获得独特的元素。然后我们得到它与第一项的长度的组合(k

于 2013-11-03T03:21:57.533 回答
1

如果您不关心输出的顺序,@DSM 的答案是正确的。但是,如果您有类似的输入[[3,2],[1,3],[7,2]]并且您需要保留输入的顺序,则需要更加复杂,因为在您的元素输入 a 的第二秒时顺序就会消失set

我将镜像他的代码,以便您看到不同之处:

from itertools import combinations, chain
from collections import OrderedDict
lol = [[3,2],[1,3],[7,2]]
k = len(lol[0])
pair_sets = [list(OrderedDict.fromkeys(chain.from_iterable(x))) for x in combinations(li,2)]
keep = [x for x in pair_sets if len(x) == k+1]
keep
[[3, 2, 1], [3, 2, 7]]
于 2013-11-03T03:52:00.113 回答
1

IIUC,这样的事情呢?

>>> from itertools import combinations
>>> lol = [[1,2],[1,3],[3,4]]
>>> k = len(lol[0])
>>> pair_sets = (set().union(*x) for x in combinations(lol,2))
>>> keep = [sorted(x) for x in pair_sets if len(x) == k+1]
>>> keep
[[1, 2, 3], [1, 3, 4]]

set().union(*x)只是获得任意集合并集的好方法;在这里,我们同样可以使用set(x[0]).union(x[1])

产生的元素pair_sets是看起来像的集合

>>> pair_sets = list(set().union(*x) for x in combinations(lol,2))
[set([1, 2, 3]), set([1, 2, 3, 4]), set([1, 3, 4])]

然后我们保留那些有 length 的k+1,对它们进行排序以得到很好的衡量。

于 2013-11-03T03:32:04.347 回答