[英]How to get a list with only unique numbers? (Python)
I want to write a program that checks for duplicate values and removes them.我想编写一个程序来检查重复值并删除它们。 So for example I want from this:
所以例如我想从这个:
list = [2,6,8,2,9,8,8,5,2,2]
To get only this:只得到这个:
uniques = [6,9,5]
I can't seem to find a good way to compare every item with each other to see if they are equal and them remove them.我似乎找不到一个好方法来比较每个项目,看看它们是否相等,然后将它们删除。 Any help will be very appreciated!
任何帮助将不胜感激!
Use collections.Counter
:使用
collections.Counter
:
>>> from collections import Counter
>>> lst = [2,6,8,2,9,8,8,5,2,2]
>>> c = Counter(lst)
>>> [x for x in c if c[x] == 1]
[6, 9, 5]
Other than using count
or in
for each element, this should be O(n) instead of O(n²).除了对每个元素使用
count
或in
之外,这应该是 O(n) 而不是 O(n²)。
If you want to preserve the order of the elements too, follow this best method :如果您也想保留元素的顺序,请遵循以下最佳方法:
uniques = list(dict.fromkeys(list))
print(uniques)
Given that you want a list of values that appear only once in your list, this should work.鉴于您想要一个仅在列表中出现一次的值列表,这应该可行。 I used a hashmap to store the count of values in the the list and then added the keys which have a count of 1 into
unqiue
.我使用哈希图将值的计数存储在列表中,然后将计数为 1 的键添加到
unqiue
中。
l = [2,6,8,2,9,8,8,5,2,2]
unique = []
count = {}
for i in l:
if count.get(i) is None:
count[i] = 1
else:
count[i]+=1
for i in count.keys():
if count[i] == 1:
unique.append(i)
print(unique)
Output输出
[6, 9, 5]
def unique(x: list):
a = set()
for i in range(len(x)):
if x.index(x[i]) == (len(x) - 1) - x[::-1].index(x[i]):
a.add(x[i])
return list(a)
print(unique([1, 2, 1, 11, 4, 4, 6, 3, 2]))
# [3, 11, 6]
list = [2,6,8,2,9,8,8,5,2,2] uniques = [] for i in range(len(list)): if list.count(list[i])==1: uniques.append(list[i])
list = [2,6,8,2,9,8,8,5,2,2] uniques = [] for i in list: if i not in uniques: uniques.append(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.