gpt4 book ai didi

python - 计算由空格分隔的未指定数量的整数并使用字典查找 python 中每个数字的出现次数

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:12 24 4
gpt4 key购买 nike

示例输出

Enter numbers separated by spaces :1 2 3 3 2 2 2 1 3 4 5 3{'1': 2, '3': 4, '2': 4, '5': 1, '4': 1}1 occurs 2 times3 occurs 4 times2 occurs 4 times5 occurs one time4 occurs one time

So I'm a total newbie at python but I was thinking of starting off like this :

d = {}     
user = input("Enter numbers separated by spaces :")
data = user.split()

除了我尝试过的每个循环都一直说我不能将 str() 转换为 int(),如果有任何帮助,我将不胜感激,我已经盯着这个问题看了几个小时了..这是我尝试过的输入是字符串,试图为字典实现类似的东西

def countdigits (aString):  
c = 10 * [0]

for e in aString:
c[int(e)] += 1

return c

def main ():
n = 0

for v in (countdigits(str(input('Enter a string: ')))):
if v == 1:
print(n, "occurs 1 time")
elif v!=0:
print(n, "occurs", v, "times")

n += 1

main()

对于给定的输出(但使用字典),我想要一个类似的解决方案

最佳答案

尝试

d = {i:data.count(i) for i in data}

for k,v in d:
print "{0} occurs {1} times\n".format(k,v)

或喜欢以下评论中的示例:

import collections

for a,b in collections.Counter(data).items():
print "{0} occurs {1} times\n".format(a,b)

关于python - 计算由空格分隔的未指定数量的整数并使用字典查找 python 中每个数字的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777357/

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