简体   繁体   English

在元组列表中查找单个唯一值

[英]Find single unique value in list of tuples

I have a list of key-value pairs in tuples, and it's known that one (and only one) of those tuples will contain a different value. 我有一个元组中的键-值对列表,而且众所周知,其中一个(只有一个)元组将包含一个不同的值。 The keys are all different. 按键都不同。 For example, 例如,

pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
         ]

I need to identify the key of the tuple with the different value. 我需要确定具有不同值的元组的键。 It is not known whether this value will be larger or smaller than the others. 不知道该值是大于还是小于其他值。

How can I accomplish this? 我该怎么做?

You can use itertools.groupby : 您可以使用itertools.groupby

import itertools
pairs = [
     ('John', 101991),
     ('Bob', 101991),
     ('Tom', 101997),
     ('Larry', 101991),
     ('Howard', 101991)
     ]
new_pairs = [(a, list(b)) for a, b in itertools.groupby(sorted(pairs, key=lambda x:x[-1]), key=lambda x:x[-1])]
new_val = [a for a, b in new_pairs if len(b) == 1]

Output: 输出:

[101997]

Edit: more efficient solution using dictionaries: 编辑:使用字典的更有效的解决方案:

from collections import defaultdict
d = defaultdict(list)
for a, b in pairs:
   d[b].append(a)

new_val = [a for a, b in d.items() if len(b) == 1]

or alternatively 或者

pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
]

stat = {}
for k, v in pairs:
    if not v in stat: stat[v] = []
    stat[v].append((k, v))

for v in stat:
    if len(stat[v]) == 1:
        print(stat[v][0][0]) #prints the key 'Tom'

I'd pick out just a list of the keys and a list of the values separately by unzipping: 通过解压缩,我只会分别选择键列表和值列表:

keys, vals = zip(*pairs)

Then I'd count the number of each unique value with numpy: 然后,我用numpy计算每个唯一值的数量:

unique, counts = np.unique(vals, return_counts=True)

And the value you want is the one with the smallest counts: 您想要的值是计数最少的值:

myminval = unique[np.argmin(counts)]

Then you find this value in your list of keys: 然后,您在键列表中找到此值:

keys[vals.index(myminval)]

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

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