How to iterate over a list of integers?
index_set = {2, 4, 5*5, 10*5, 15*5, 20*5, 30*5, 40*5, 45*5}
for index in index_set:
print(index, end=',')
Output
225,2,4,100,200,75,50,150,25,
Desired output
2, 4, 25, 50, 75, 100, 150, 200, 225
CodePudding user response:
No need for the loop:
index_set = {2, 4, 5*5, 10*5, 15*5, 20*5, 30*5, 40*5, 45*5}
index_set = ", ".join([str(i) for i in sorted(index_set)])
print(index_set)
Output:
2, 4, 25, 50, 75, 100, 150, 200, 225
CodePudding user response:
if you just want to sort it you can use list comprehension:
print(sorted([x for x in index_set]))
or convert it directly into a list:
print(sorted(list(index_set)))
output:
[2, 4, 25, 50, 75, 100, 150, 200, 225]
or, using a similar approach as you did:
for index in sorted(index_set):
print(index,end=', ')
output:
2, 4, 25, 50, 75, 100, 150, 200, 225
CodePudding user response:
try wrapping your index_set with the sorted function:
for index in sorted(index_set):
print(index, end=', ')
