gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:27 25 4
gpt4 key购买 nike

这是我的第一个 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])

关于python - 第一个 python 程序看起来不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34172263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com