【问题标题】:Filter list, only unique values - with python过滤器列表,只有唯一值 - 使用 python
【发布时间】:2012-10-14 03:06:37
【问题描述】:

我想知道如何获取一个列表,例如 a = [1, 5, 2, 5, 1],并让它过滤掉唯一值,以便它只返回一个仅在列表中出现一次的数字.所以它会给我 a=[2] 作为结果。

我能够弄清楚如何过滤掉重复项,现在我该如何去除重复项?

不需要直截了当的答案,欢迎提供一点提示或提示 :)

我可以在 stackoverflow 上找到这个。它做了我想要的,但是我不明白代码,有人可以帮我分解一下吗?

d = {}
for i in l: d[i] = d.has_key(i)

[k for k in d.keys() if not d[k]]

【问题讨论】:

    标签: python filter


    【解决方案1】:
    >>> a = [1, 5, 2, 5, 1]
    >>> from collections import Counter
    >>> [k for k, c in Counter(a).iteritems() if c == 1]
    [2]
    

    【讨论】:

      【解决方案2】:

      听听您的代码的作用:

      d = {}
      for i in list:
          # if the item is already in the dictionary then map it to True,
          # otherwise map it to False 
          # the first time a given item is seen it will be assigned False,
          # the next time True
          d[i] = d.has_key(i)
      
      # pull out all the keys in the dictionary that are equal to False
      # these are items in the original list that were only seen once in the loop
      [k for k in d.keys() if not d[k]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多