简体   繁体   English

从排列列表中获取所有唯一组合

[英]Get all unique combinations from list of permutations

TL/DR TL / DR

Given X = {(A,B),(B,C),(D,E),(B,A),(C,B)} (where X is a set ) 给定X = {(A,B),(B,C),(D,E),(B,A),(C,B)} (其中Xset

How do I filter for the subtuples which show a unique combination (instead of a unique permutation) such that X becomes {(A,B),(B,C),(D,E))} 如何过滤显示唯一组合(而不是唯一排列)的子元组,使得X变成{(A,B),(B,C),(D,E))}

Longer form 更长的形式

Somewhat of an inverse problem from most of the combination/permutation questions on here. 这里的大多数组合/置换问题都有些逆问题。

I have a set of tuples (outer tuples), where each tuple has 2 elements, both of which are also tuples (inner tuples), and each sub-tuple has two elements, both of which are integers. 我有一组元组(外部元组),其中每个元组都有2个元素,两个元素也都是元组(内部元组),每个子元组都有两个元素,两个元素都是整数。

As an example, the set with three elements might look like 例如,包含三个元素的集合可能看起来像

X = { ( (1,2),(2,3) ), ( (1,3),(1,2) ), ( (2,3),(1,2) ) }

While all the outer tuples are unique, I'd like to build a subset which contains the set of unqiue tuples where the ORDER of the two inner tuples is irrelevant (ie a set of unique combinations). 尽管所有外部元组都是唯一的,但我想构建一个子集,其中包含两个内部元组的ORDER不相关的非队列元组(即一组唯一组合)。 In the example above this would reduce to; 在上面的示例中,这将减少为;

X = { ( (1,2),(2,3) ), ( (1,3),(1,2) )}

Because 因为

( (1, 2),(2,3) ) and ( (2,3),(1,2) ) )

are both just combinations of (1, 2) and (2,3) . 都是(1, 2)(2,3)

There are obvious brute-force/for-loop approaches to this but they don't feel very Pythonic. 有很明显的蛮力/循环方法,但是它们感觉不太像Python。

Maybe leveraging itertools and map ? 也许利用itertoolsmap

You can apply the sorted function on your elements using map and then use a set comprehension to get the unique elements : 您可以使用map在元素上应用sorted函数,然后使用集合理解来获取唯一元素:

>>> new={tuple(i) for i in map(sorted,X)}
>>> new
set([('B', 'C'), ('A', 'B'), ('D', 'E')])

But note that since sorted convert your elements to list you need to reverse them to tuple because lists are not hashable. 但是请注意,由于sorted后将元素转换为列表,因此您需要将它们反转为tuple因为列表不可散列。

One way would be to sort the tuples, then make a new set. 一种方法是元组进行排序 ,然后进行新的设置。 (A, B) and (B, A) will both have been sorted to (A, B), and thus only occur once. (A,B)和(B,A)都将被排序为(A,B),因此仅出现一次。

def to_sorted(t):
    return tuple(sorted(t))

Xnew = {to_sorted(t) for t in X}

Another is to not use tuples at all -- tuples are ordered, and you don't care about the order. 另一个是根本不使用元组-元组是有序的,而您并不关心该顺序。 You could use sets. 您可以使用集合。 frozensets are immutable sets that can be elements of other sets: Frozensets是不可变的集合,可以是其他集合的元素:

Xnew = {frozenset(t) for t in X}

I like this slightly better, but 1) it doesn't work if your tuples contain multiples, and 2) now you have frozensets instead of tuples, your other code probably needs changing. 我稍微喜欢上一点,但是1)如果您的元组包含倍数,它将不起作用,以及2)现在您拥有了不动的集合而不是元组,您的其他代码可能需要更改。

进一步简化了一个步骤(删除地图):

new = {tuple(sorted(n)) for n in X}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM