Python 增加键值对的程序优化和字典工作

Python 增加键值对的程序优化和字典工作,python,python-3.x,Python,Python 3.x,这是我计算元音数的程序 '''Program to count number of vowels''' str=input("Enter a string\n") a=0 e=0 i=0 o=0 u=0 for x in str: if x=='a': a=a+1 continue if x=='e': e=e+1 continue if x=='i': i=i+1 conti

这是我计算元音数的程序

'''Program to count number of vowels'''
str=input("Enter a string\n")
a=0
e=0
i=0
o=0
u=0
for x in str:
    if x=='a':
        a=a+1
        continue
    if x=='e':
        e=e+1
        continue
    if x=='i':
        i=i+1
        continue
    if x=='o':
        o=o+1
        continue
    if x=='u':
        u=u+1
        continue
count={}
if a>0:
    count['a']=a
if e>0:
    count['e']=e
if i>0:
    count['i']=i
if o>0:
    count['o']=o
if u>0:
    count['u']=u
print(count)
如何在填充字典的过程中改进初始循环以进行比较

在多次运行程序时,我获得了以下输出:

>>> 
Enter a string
abcdefgh
{'e': 1, 'a': 1}
>>> ================================ RESTART ================================
>>> 
Enter a string
abcdefghijklmnopqrstuvwxyz
{'u': 1, 'a': 1, 'o': 1, 'e': 1, 'i': 1}
>>> ================================ RESTART ================================
>>> 
Enter a string
abcdeabcdeiopiop
{'a': 2, 'o': 2, 'i': 2, 'e': 2}
从这一点上,我无法计算出添加到字典中的键值对与我的期望值相比究竟是多少:

Case 1:
{'a':1, 'e':1}
Case 2:
{'a':1, 'e':1, 'i':1, 'o':1, 'u':1}
Case 3:
{'a':2, 'e':2, 'i':2, 'o':2}

非常感谢您的帮助。

只要把
a=0e=0i=0o=0u=0
放在这样一本字典里:

myDict = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
for x in string:
    myDict[x] += 1 
print myDict
myDict = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
for x in string:
    try:
        myDict[x] += 1
    except KeyError:
        continue
print myDict
如果该值不是以下值之一,则会出现
keyrerror
raise

所以你可以这样做:

myDict = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
for x in string:
    myDict[x] += 1 
print myDict
myDict = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
for x in string:
    try:
        myDict[x] += 1
    except KeyError:
        continue
print myDict
注意:我已将名称
str
更改为
string


您还可以通过@Amber看到一个非常好的解决方案。一种更具python风格的方法是:

'''Program to count number of vowels'''
s = input("Enter a string\n")
count = {v: s.count(v) for v in "aeiou" if s.count(v) > 0}
print(count)
您不应该使用
str
作为变量名,因为这是内置字符串类型的名称

>>> import collections
>>> s = "aacbed"
>>> count = collections.Counter(c for c in s if c in "aeiou")
>>> count
Counter({'a': 2, 'e': 1})
或者-如果您确实需要维护插入顺序:

>>> s = 'debcaa'
>>> count=collections.OrderedDict((c, s.count(c)) for c in s if c in "aeiou")
>>> count
OrderedDict([('e', 1), ('a', 2)])
最后,如果您想要词典排序,您可以将dict/counter/OrderedDict转换为元组列表:

>>> sorted(count.items())
[('a', 2), ('e', 1)]
如果您想要按字典顺序排列的信息:

>>> sorted_count = collections.OrderedDict(sorted(count.items()))
>>> sorted_count
OrderedDict([('a', 2), ('e', 1)])

你的意思是你对字典中键的顺序感到惊讶吗?字典不保持顺序。因此,您的程序只能正常工作。如果要保持插入键的顺序,则需要使用集合。OrderedDict这会导致错误,因为并非所有字符都在字典中,例如myDict['b']将给出一个错误,因此仍然需要if比较优化if比较的任何想法,或者我应该保持它的简单性。
collections.OrderedDict((c,s.count(c)),如果c在“aeiou”中,则c在“aeiou”中。
-二次时间,并且它不会产生
aeiou
对预期的OP进行排序。