【问题标题】:How to get only unique values from a list in Python [closed]如何从 Python 中的列表中仅获取唯一值 [关闭]
【发布时间】:2020-06-16 09:12:44
【问题描述】:

所以我只想选择数组的唯一字符,期望的输出应该是:

输入:4,5,6,4,2,2,9

输出:5,6,9

我试过这些代码:

arr = [4,5,6,4,2,2,9]
unique = list(set(arr))

但输出是:4,5,6,2,9

没有numpy可以做到吗?

【问题讨论】:

标签: python


【解决方案1】:

您可以计算元素的频率并选择频率为 1 的元素,如下所示。

from collections import Counter
arr = ...
unique = [k for k,v in Counter(arr).items() if v == 1]

【讨论】:

  • 谢谢它的工作,但你能告诉我 Counter 是如何工作的吗?
  • 由于计数是一个常见的用例,Python 提供了Counter 类来方便计数。它是dict 的子类,专门用于计算可散列对象并维护对象频率。至于怎么算,it merely iterates thru the iterable and counts the elements:) 更多详情请参考其docs
【解决方案2】:

您可以使用集合中的计数器。这是一个示例python代码:

from collections import Counter
arr = [4,5,6,4,2,2,9]
d = Counter(arr)
unique = [x for x in d if d[x] == 1]
print(a)

计数器返回一个字典,其中数组项作为键,项频率作为值。例如,如果数组arr = [4,5,6,4,2,2,9] 那么计数器提供以下字典:

d = {
1: 2, 
2: 1, 
3: 1, 
4: 1,
5: 3,
6: 1
}

【讨论】:

    【解决方案3】:

    您所做的将返回数组中的所有数字,而不会重复。 你可以像这样做你想做的事:

    [x for x in array if array.count(x) == 1]

    但这不是很有效,因为它需要扫描整个数组 对于每个调用的 count()。更快的方法是:

    from collections import defaultdict
    counts = defaultdict(int)  # count how many times every number appears in the array, for example {5:1, 6:1, 9:1, 4:2, 2:2}. defaultdict(int) means that values default to 0.
    for x in arr:
        counts[x] += 1
    result = [number for number, count in counts.items() if count == 1 ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2014-11-20
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 2015-04-26
      相关资源
      最近更新 更多