gpt4 book ai didi

python - 检查字典中的唯一值并返回列表

转载 作者:行者123 更新时间:2023-11-28 22:42:17 25 4
gpt4 key购买 nike

我已经为这个练习苦苦挣扎了几天,我找到的每个近似值都有一个新问题,我的想法是在字典中找到那些唯一的值,并返回一个包含键的列表

例如:如果 aDictionary = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0} 那么你的函数应该返回 [1, 3, 8 ],因为值 1,2 和 4 只出现一次。

这是我到目前为止尝试过的:

def existsOnce(aDict):

counting = {}
tempList = []

for k in aDict.keys():
print k,
print aDict[k]


print 'values are:'
for v in aDict.values():
print v,
counting[v] = counting.get(v,0)+1
print counting[v]
tempNumbers = counting[v]
tempList.append(tempNumbers)
print tempList

如果我这样做,我可以指向并删除大于 1 的那些,但问题仍然存在,我将有一个零,我不想要它,因为它在原始列表中不是唯一的。

def existsOnce2(aDict):

# import Counter module in the top with `from collections import Counter`

c = Counter()

for letter in 'here is a sample of english text':
c[letter] += 1
if c[letter] == 1:
print c[letter],':',letter

我尝试用这种方式处理整数并检查哪些是第一次出现的,但无法将其翻译成字典或从这里继续。另外我不确定答案中是否允许导入模块,并且肯定必须是一种没有外部模块的方法。

def existsOnce3(aDict):

vals = {}
for i in aDict.values():
for j in set(str(i)):
vals[j] = 1+ vals.get(j,0)
print vals

'''till here I get a counter of how many times a value appears in the original dictionary, now I should delete those bigger than 1'''
temp_vals = vals.copy()
for x in vals:
if vals[x] > 1:
print 'delete this: ', 'key:',x,'value:', vals[x]
temp_vals.pop(x)
else:
pass
print 'temporary dictionary values:', temp_vals
'''till here I reduced down the values that appear once, 1, 2 and 4, now I would need the go back and check the original dictionary and return the keys
Original dictionary: {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}
temp_vals {'1': 1, '2': 1, '4': 1}
keys on temp_vals (1,2,4) are the values associated to the keys I got to retrieve from original dictionary (1,3,8)
'''
print '---'

temp_list = []
for eachTempVal in temp_vals:
temp_list.append(eachTempVal)
print 'temporary list values:', temp_list
''' till here I got a temporary list with the values I need to search in aDict'''
print '---'
for eachListVal in temp_list:
print 'eachListVal:', eachListVal
for k,v in aDict.iteritems():
print 'key:',k,'value:',v

从这里我无法出于任何原因获取值并比较它们,我尝试使用如下语句提取值:

if v == eachListVal:
do something

但我做错了,无法访问这些值。

最佳答案

您只需要使用您的 vals 字典,并保留来自 aDict 的键,其值在 vals 中具有 count == 1 然后调用排序以获得排序的输出列表:

def existsOnce3(aDict):  
vals = {}
# create dict to sum all value counts
for i in aDict.values():
vals.setdefault(i,0)
vals[i] += 1
# use each v/val from aDict as the key to vals
# keeping each k/key from aDict if the count is 1
return sorted(k for k, v in aDict.items() if vals[v] == 1)

使用 collections.Counter dict 进行计数,只需对您的值调用 Counter,然后应用相同的逻辑,只需保留来自 Counter dict 的每个具有 v count == 1 的 k:

from collections import Counter
cn = Counter(aDict.values())
print(sorted(k for k,v in aDict.items() if cn[v] == 1))

关于python - 检查字典中的唯一值并返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com