【问题标题】:Program optimisation and working of dictionary in adding key value pairs字典添加键值对的程序优化与工作
【发布时间】:2013-12-24 11:07:19
【问题描述】:

这是我计算元音数量的程序

'''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}

感谢任何帮助。

【问题讨论】:

  • 您的意思是您对字典中的键顺序感到惊讶吗?
  • 字典不保持顺序。所以,你的程序只能正常工作。如果您想保持插入键的顺序,您需要使用Collections.OrderedDict

标签: python python-3.x


【解决方案1】:
>>> 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)])

【讨论】:

  • collections.OrderedDict((c, s.count(c)) for c in s if c in "aeiou") - 二次时间,并且它不会产生aeiou 的顺序,无论如何都是预期的 OP。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    只需将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
    

    如果该值不是以下之一,则将出现 raiseKeyError

    所以你可以这样做:

    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 here的一个很好的解决方案

    【讨论】:

    • 这会产生错误,因为并非所有字符都在字典中,因此例如 myDict['b'] 会产生错误,因此如果仍然需要比较
    • 任何关于优化的想法,如果比较或者我应该保持简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2018-05-27
    • 2011-07-17
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多