从列表中
l =[(3,4),(2,3),(4,3),(3,2)]
我想以相反的顺序排列具有相同成员的对的所有第二次出现。即,结果应为
[(3,4),(2,3)]
在Python中最简洁的方法是什么?
答案 0 :(得分:1)
或者,人们可能会以更冗长的方式做到这一点:
l = [(3,4),(2,3),(4,3),(3,2)]
L = []
omega = set([])
for a,b in l:
key = (min(a,b), max(a,b))
if key in omega:
continue
omega.add(key)
L.append((a,b))
print(L)
答案 1 :(得分:1)
如果我们只想保留每对中的第一个元组:
l =[(3,4),(2,3),(4,3),(3,2), (3, 3), (5, 6)]
def first_tuples(l):
# We could use a list to keep track of the already seen
# tuples, but checking if they are in a set is faster
already_seen = set()
out = []
for tup in l:
if set(tup) not in already_seen:
out.append(tup)
# As sets can only contain hashables, we use a
# frozenset here
already_seen.add(frozenset(tup))
return out
print(first_tuples(l))
# [(3, 4), (2, 3), (3, 3), (5, 6)]
答案 2 :(得分:0)
这应该是诀窍:
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:])]
Out[23]: [(3, 4), (2, 3)]
使用不同的顺序扩展初始列表:
l =[(3,4),(2,3),(4,3),(3,2), (1,3), (3,1)]
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:])]
Out[25]: [(3, 4), (2, 3), (1, 3)]
并且,取决于每个元组是否保证有伴随的姐妹"反转元组,逻辑可能会改变,以保持"单身"元组:
l = [(3, 4), (2, 3), (4, 3), (3, 2), (1, 3), (3, 1), (10, 11), (10, 12)]
[x for i, x in enumerate(l) if any(y[::-1] == x for y in l[i:]) or not any(y[::-1] == x for y in l)]
Out[35]: [(3, 4), (2, 3), (1, 3), (10, 11), (10, 12)]
答案 3 :(得分:0)
my_tuple_list = [(3,4),(2,3),(4,3),(3,2)]
set((left, right) if left < right else (right, left) for left, right in my_tuple_list)
>>> {(2, 3), (3, 4)}
它只是创建一组所有元组,如果第一个成员是&gt;,则预先交换其成员。第二个成员。