簡體   English   中英

如何在 python 中找到多個不重復的數字?

[英]how to find multiple non-repeating numbers in python?

我有一個在列表中查找非重復元素的方法:

def dupes(a):
    s = {}
    for ele in a:
        if ele not in s:
            s[ele] = 1
        else:
            s[ele] += 1
    for x in s:
        if s[x] == 1:
            return 'this is the only non-repeating element value is :', s[x], 'and the key is :', x
    return

l = [4, 7, 4, 5, 7, 6, 5, 6, 10]
cd = dupes(l)
print("This is dupes: ", cd)

代碼運行成功,下面是output:

This is dupes:  ('this is the only non-repeating element value is :', 1, 'and the key is :', 10)

但是當我嘗試在列表中添加多個非重復元素時,output 不會改變。 例如,如果我在列表末尾添加 11,則 output 仍然與上面相同。

任何想法?

您可以使用列表推導獲取值為 1 的所有鍵。

nondupes = [k for (k,v) in s.items() if v==1]
return 'Non-repeating elements: ' + str(nondupes)

此外,您可以用collections.Counter替換所有計數代碼:

s = Counter(a)
def dupes(a):
    s = {}
    for ele in a:
        if ele not in s:
            s[ele] = 1
        else:
            s[ele] += 1
    count = 0
    keys = []
    for x in s:
        if s[x] == 1:
            count += 1
            keys.append(x)
    return 'this is the only non-repeating element value is :', count, 'and the key is :', keys

那會很好。

實際上,當您在第 10 行返回時,function 就結束了。 這是為了以防您還不了解列表理解,因為許多人已經使用該技術為您提供了解決方案。 我只會給你一個簡單的解決方案,它將返回一個非重復數字的列表。

def dupes(a):
    s = {}
    non_dupes = []
    for ele in a:
        if ele not in s:
            s[ele] = 1
        else:
            s[ele] += 1
    for x in s:
        if s[x] == 1:
            non_dupes.append(x)
    return non_dupes

l = [4, 7, 4, 5, 7, 6, 5, 6, 10, 11]
cd = dupes(l)
print("This is dupes: ", cd)

您可以使用Counter簡潔地實現上述目標:

from collections import Counter
l = [4, 7, 4, 5, 7, 6, 5, 6, 10]
c = Counter(l)
dupes = list(key for key in c if c[key] > 1)
print("This is dupes: ", dupes)

Output:

This is dupes:  [4, 7, 5, 6]

您遇到的問題是您從 function 過早返回,其中包含第一個重復的字符串。 副本的 rest 丟失。

你已經有了重復的列表,讓我們只return數據,這樣我們就可以將結果的計算與結果的顯示分開。

return list(e for e in s if s[e] > 1)

您可以使用count() function 在一行 python 代碼中輕松解決此問題:

l = [4, 7, 4, 5, 7, 6, 5, 6, 10 ,11]

only_one_time = [e for e in l if l.count(e) < 2]

print(only_one_time)

給定的代碼返回它遇到的第一個非重復元素。 例如,如果輸入列表是l = [12, 11, 4, 7, 4, 5, 7, 6, 5, 6, 10] ,則 output 將是This is dupes: ('this is the only non-repeating element value is:', 1, 'and the key is:', 12)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM