Skip to main content
 首页 » 编程设计

python之第一个 python 程序看起来不正确

2025年05月04日15mq0036

这是我的第一个 python 程序,我已经阅读了一段时间有关 python 的内容并且该程序可以运行,但我认为我没有正确完成所有操作。这是代码

dict_top = {'a':[0], 'b':[0], 'c':[0], 'd':[0], 'e':[0], 'f':[0], 'g':[0], 
            'h':[0], 'i':[0], 'j':[0], 'k':[0], 'l':[0], 'm':[0], 'n':[0], 
            'o':[0], 'p':[0], 'q':[0], 'r':[0], 's':[0], 't':[0], 'u':[0], 
            'v':[0], 'w':[0], 'x':[0], 'y':[0], 'z':[0]} 
 
with open('planet-names.txt') as file_object: # this will automatically close 
    for planet_name in file_object: 
        for letter in planet_name: 
            if letter in dict_top: 
                a = dict_top[letter][0] 
                dict_top[letter][0] = a + 1 
                dict_top[letter].append(planet_name.find(letter)) 
 
print(dict_top) 

planet-names.txt 只是每行一个行星的名字 我想计算 A、B、C 在一堆行星的每个名称中出现的次数 并记录他们被发现的不同位置。

这不是作业!我正在尝试制作一个随机生成行星名称的程序!!!

你应该如何编写像 dict_top 这样的代码?我花了一个小时才打完所有这些

请您参考如下方法:

使用collections.Counter

import collections 
c = collections.Counter() 
with open('planet-names.txt') as file_object: # this will automatically close 
    for planet_name in file_object: 
        c.update(collections.Counter(planet_name)) 
 
print c 

或者您可以使用 dict.fromkeys

创建字典
import string 
dict_top = dict.fromkeys(list(string.ascii_lowercase),[0])