使特定元素唯一的元组序列 [英] Making a sequence of tuples unique by a specific element
问题描述
所以我有一个元组元组
a = ((1, 2), (7, 2), (5, 2), (3, 4), (8, 4))
我想从 'a' 中删除所有具有共同第二个元素的元组,除了一个(它们中的任何一个).
对于上面的例子,我想要新的输出 a = ((1,2),(3,4))
换句话说,我想消除元组的第二个位置被认为是重复元素的元组.
我想知道实现这一目标的最有效方法,还想知道我是否可以用列表而不是元组来做同样的事情?
您可以从您的元素创建一个字典,以您希望唯一的任何内容作为键,然后提取值.这适用于唯一"子元素可散列的任何内容.整数是可散列的:
def unique_by_key(elements, key=None):如果键是无:# 无键:整个元素必须是唯一的键 = lambda e: ereturn {key(el): el for el in elements}.values()
这个函数非常通用;它可以用于通过任何特征提取唯一"元素,只要 key
可调用返回的任何内容都可以用作字典中的键.顺序不会被保留,目前每个键的最后一个元素获胜.
通过上述函数,您可以使用 operator.itemgetter()
对象 或 lambda 来从每个元素中提取您的第二个值.然后这适用于元组序列和列表序列:
from 操作符导入 itemgetterunique_by_second_element = unique_by_key(a, key=itemgetter(1))
演示:
<预><代码>>>>from 操作符导入 itemgetter>>>a = ((1, 2), (7, 2), (5, 2), (3, 4), (8, 4))>>>unique_by_key(a, key=itemgetter(1))[(5, 2), (8, 4)]>>>b = [[1, 2], [7, 2], [5, 2], [3, 4], [8, 4]]>>>unique_by_key(b, key=itemgetter(1))[[5, 2], [8, 4]]注意该函数总是返回一个list;您始终可以通过对结果调用 tuple()
将其转换回来.
So I have a tuple of tuples
a = ((1, 2), (7, 2), (5, 2), (3, 4), (8, 4))
I would like to remove all the tuples from 'a' which have the a common second element, except for one (any one of them).
For the example above I would like the new output a = ((1,2),(3,4))
In other words I would like to eliminate tuples which are considered duplicate elements in the second position of the tuple.
I would like to know the most efficient way to achieve this, and also like to know if I can do the same with lists instead of tuples?
You could create a dictionary from your elements, with whatever you wanted to be unique as the key, then extracting the values. This works for anything where the 'unique' sub-element is hashable. Integers are hashable:
def unique_by_key(elements, key=None):
if key is None:
# no key: the whole element must be unique
key = lambda e: e
return {key(el): el for el in elements}.values()
This function is pretty generic; it can be used to extract 'unique' elements by any trait, as long as whatever the key
callable returns can be used as a key in a dictionary. Order will not be preserved, and currently the last element per key wins.
With the above function you can use a operator.itemgetter()
object or a lambda to extract your second value from each element. This then works for both a sequence of tuples and a sequence of lists:
from operator import itemgetter
unique_by_second_element = unique_by_key(a, key=itemgetter(1))
Demo:
>>> from operator import itemgetter
>>> a = ((1, 2), (7, 2), (5, 2), (3, 4), (8, 4))
>>> unique_by_key(a, key=itemgetter(1))
[(5, 2), (8, 4)]
>>> b = [[1, 2], [7, 2], [5, 2], [3, 4], [8, 4]]
>>> unique_by_key(b, key=itemgetter(1))
[[5, 2], [8, 4]]
Note that the function always returns a list; you can always convert that back by calling tuple()
on the result.
这篇关于使特定元素唯一的元组序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!