简体   繁体   English

在python中制作唯一列表

[英]Making unique list in python

What is the most pythonic way of making a list unique using custom equality operator? 使用自定义相等运算符使列表唯一的最有效的方法是什么?

For instance you have a list of dicts L , and you want a new list M such that for all dicts d , e in M and one specific x 例如,您有一个字典L的列表,并且您想要一个新列表M ,以便对所有字典dM e和一个特定的x

d[x] != e[x]

How can this be done? 如何才能做到这一点?

In your case (and all cases where equivalence boils down to the equivalence of some kind of key), you can simply construct a dictionary, where the keys are the values you want to compare: 在您的情况下(以及所有等效性归结为某种键的等效性的所有情况),您可以简单地构造一个字典,其中的键是您要比较的值:

L = [{'key': 'foo', 'v': 42}, {'key': 'bar', 'v': 43}, {'key': 'foo', 'v': 44}]
x = 'key'
M = {d[x]:d for d in L}.values()
# In old Python versions: dict((d[x],d for d in L)).values()

Note that the result is not deterministic, both 请注意,结果不是确定性的,两者

[{'key': 'foo', 'v': 44}, {'key': 'bar', 'v': 43}]

and

[{'key': 'foo', 'v': 42}, {'key': 'bar', 'v': 43}]

are valid results. 是有效的结果。

In the general case, simply check all accepted values: 在一般情况下,只需检查所有接受的值:

def unique(iterable, is_eq):
  tmp = []
  for el in iterable:
    if not any(is_eq(inTmp, el) for inTmp in tmp):
      tmp.append(is_eq)
  return tmp

Note that this means that your comparison function will be called O(n²) times instead of n times. 请注意,这意味着您的比较函数将被称为O(n²)次而不是n次。

Based on FUD's comment to phihag. 基于FUD对phihag的评论。 Note that key function must return a hashable value. 请注意, key函数必须返回可哈希值。

def unique(iterable, key=lambda x : x):
    seen = set()
    res = []
    for item in iterable:
        k = key(item)
        if k not in seen:
            res.append(item)
            seen.add(k)
    return res

from operator import itemgetter
L = [{'key': 'foo', 'v': 42}, {'key': 'bar', 'v': 43}, {'key': 'foo', 'v': 44}]
print unique(L, key=itemgetter('key'))
#[{'key': 'foo', 'v': 42}, {'key': 'bar', 'v': 43}]

I'm not sure this sort of thing admits a one-liner, but it seems to me that the set class is the key to what you want. 我不确定这种事情是否允许单行,但是在我看来, set类是您想要的关键。

M = []
uniques = set(d[x] for d in L)
for d in L:
    if d[x] in uniques:
        uniques.remove(d[x])
        M.append(d)

Note: phihag's answer seems more Pythonic, but this might be a bit more self-documenting 注意:phihag的答案似乎更像Python,但是这可能更多是自我记录

Using dictionary comprehension: 使用字典理解:

def unique(itrable,key):
    return {key(x):x for x in itrable}.values()

>>> unique('abcdbbcdab', lambda x: x)
['a', 'c', 'b', 'd']

>>> unique([10, -20, 20, 30], lambda x: abs(x))
[10, 20, 30]

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

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