我最终得到的输出是:2、1、8、0、0,应该是:2、1、3、1、4,我正在使用PyCharm CE 2016.2.3和Python 3.6.6谢谢在您的时间里!
lotto = {
'1': 0,
'2': 0,
'3': 0,
'4': 0,
'5': 0
}
test_list = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
for i in test_list:
if test_list[i] == 1:
lotto['1'] += 1
if test_list[i] == 2:
lotto['2'] += 1
if test_list[i] == 3:
lotto['3'] += 1
if test_list[i] == 4:
lotto['4'] += 1
if test_list[i] == 5:
lotto['5'] += 1
for i in lotto:
print(lotto[i], end=",")
答案 0 :(得分:0)
好像您需要用i代替test_list [i],因为我已经在遍历test_list并检查每个数字,而不是索引。另外,出于良好的惯例,在第一个if块之后,将每个if都更改为elif。
lotto = {
'1': 0,
'2': 0,
'3': 0,
'4': 0,
'5': 0
}
test_list = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
for i in test_list:
if i == 1:
lotto['1'] = lotto['1'] + 1
elif i == 2:
lotto['2'] += 1
elif i == 3:
lotto['3'] += 1
elif i == 4:
lotto['4'] += 1
elif i == 5:
lotto['5'] += 1
i+=1
for i in lotto:
print(lotto[i], end=",")
答案 1 :(得分:0)
您的代码必须为:
lotto = {
'1': 0,
'2': 0,
'3': 0,
'4': 0,
'5': 0
}
test_list = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
for i in test_list:
i = str(i)
lotto[i] = lotto[i] + 1
for i in lotto:
print(lotto[i], end=",")
答案 2 :(得分:0)
棕色!
您可以使用在python中使用列表的更好方法来替换for循环:
library(purrr)
map(list_ok, function(x) map_dbl(seq_along(list_ok), function(y) x[[y]]))
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 6 7 8 9 10
[[3]]
[1] 11 12 13 14 15
[[4]]
[1] 16 17 18 19 20
[[5]]
[1] 21 22 23 24 25
使用test_list中的数字来引用键值。
for number in test_list:
lotto[str(number)] += 1
结果是:
lotto = {
'1': 0,
'2': 0,
'3': 0,
'4': 0,
'5': 0 }
test_list = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
for number in test_list:
lotto[str(number)] += 1
答案 3 :(得分:0)
您可以使用collections.Counter
重新实现代码:
from collections import Counter
test_list = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
lotto = Counter(map(str, test_list))
print(','.join(map(str, lotto.values())))