Python &引用;我如何过滤字典中的所有内容,除了具有最小非零值的项?
我当前的代码:Python &引用;我如何过滤字典中的所有内容,除了具有最小非零值的项?,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我当前的代码: string = str(input("please input a string: ")) vowel_count = {c:string.count(c) for c in 'aeoiu'} print(vowel_count) 对不起,我以前确实有一篇帖子,但它有两个问题 在我尝试使用for循环进行不同操作之前,我尝试在字典中找到0以上的最低数字,然后打印它们。即使有多个具有相同值 如果有人能给我指出正确的方向那就太好了 谢谢 charlie查找最小的非零值: >
string = str(input("please input a string: "))
vowel_count = {c:string.count(c) for c in 'aeoiu'}
print(vowel_count)
对不起,我以前确实有一篇帖子,但它有两个问题
在我尝试使用for循环进行不同操作之前,我尝试在字典中找到0以上的最低数字,然后打印它们。即使有多个具有相同值
如果有人能给我指出正确的方向那就太好了
谢谢
charlie查找最小的非零值:
>>> string = 'smallest nonzero values'
>>> vowel_count = {c:string.count(c) for c in 'aeoiu'}
>>> m = min(cnt for ch, cnt in vowel_count.items() if cnt > 0)
按数字筛选字母表:
>>> {ch: cnt for ch, cnt in vowel_count.items() if cnt == m}
{'u': 1}
>>> ['{}={}'.format(ch, cnt) for ch, cnt in vowel_count.items() if cnt == m]
['u=1']
>>> ', '.join('{}={}'.format(ch, cnt) for ch, cnt in vowel_count.items() if cnt == m)
'u=1'
注意:如果没有元音,min(…)
将引发ValueError
。您需要捕获异常
>>> vowel_count = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
>>> min(cnt for ch, cnt in vowel_count.items() if cnt > 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
元音_count={'a':0,'e':0,'i':0,'o':0,'u':0}
>>>最小值(如果cnt>0,则表示ch的cnt,元音中的cnt_count.items())
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:min()参数是空序列
我不知道你对这种情况有什么要求。我把它留给你。如果输入是
最小的非零值,那么预期的输出是什么<代码>{a':2,'e':3,'u':1,'o':2}
/{u':1}
/u
//1
?您的意思是在您的听写理解中添加'if string.count(c)`吗?预期输出为:u=1