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

时间:2013-12-24 11:07:19

标签: 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
        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}

感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

>>> 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)]

如果你想要一个按字典顺序排列的OrderedDict:

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

答案 1 :(得分:1)

只需将a=0 e=0 i=0 o=0 u=0放入字典中:

myDict = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
for x in string:
    myDict[x] += 1 
print myDict

如果该值不是以下值之一,则会raise KeyError 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更改为{{1}}

你也可以通过@Amber here

看到一个非常好的解决方案

答案 2 :(得分:1)

更多Pythonic的方式来做你想要的是:

'''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作为变量名,因为这是内置字符串类型的名称。