回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我已经在这个练习中挣扎了几天了,我发现的每个近似值都有一个新问题,我的想法是在字典中找到那些唯一的值,并返回一个带有键的列表</p>
<p>例如:
如果<code>aDictionary = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}</code>,那么函数应该返回<code>[1, 3, 8]</code>,因为值1、2和4只出现一次。</p>
<p>这就是我目前所做的尝试:</p>
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(tempNumbers)
print tempList
</code></pre>
<p>如果我这样做,我可以指出并删除那些大于1的,但问题仍然存在,我将有一个零,我不希望它在原始列表中不是唯一的。</p>
<pre><code>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
</code></pre>
<p>我试着用整数来表示,并检查第一次出现的是哪一个,但不能把它翻译成字典,也不能从这里继续。另外,我不确定答案中是否允许导入模块,而且肯定必须是一种没有外部模块的方法。</p>
<pre><code>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
</code></pre>
<p>从这里开始,无论出于何种原因,我都无法获取这些值并对它们进行比较,我尝试用如下语句提取这些值:</p>
<pre><code>if v == eachListVal:
do something
</code></pre>
<p>但我做错了,无法获得价值观。</p>