Something goes wrong during the first for loop
Something goes wrong during the first for loop
I end up with the output: 2,1,8,0,0, It should be: 2,1,3,1,4, I'm using PyCharm CE 2016.2.3 and Python 3.6.6 Thank you for your time!
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=",")
test_list[i] == 1
i==1
The
for ... in ...
loop does not index the list but iterate through every item in the list.– Kevin Fang
Aug 27 at 1:26
for ... in ...
Thank you so much! I was making it more complicated than it needed to be. Especially for something so simple.
– C. Brown
Aug 27 at 1:29
4 Answers
4
Your code needs to be:
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=",")
Brown !
You can replace the for loop with a better way to use lists in python:
for number in test_list:
lotto[str(number)] += 1
Use numbers in test_list to refer in key value.
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
And the result is:
'1': 2, '2': 1, '3': 3, '4': 1, '5': 4
Thank you! It's amazing to see how everyone does something a bit differently.
– C. Brown
Aug 27 at 2:03
Looks like you need to replace test_list[i] with just i because i is already iterating through test_list and checking each number, not the index. Also, just for good practice, after the first if block, change each if to 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=",")
You can re-implemented your code with collections.Counter
:
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())))
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Change
test_list[i] == 1
toi==1
.– Kevin Fang
Aug 27 at 1:24