Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an indexed loop over a list in Python?

I have the following code that takes a string biology_score and after splitting it, converts it into a string ('b'). The desired output is to produce what I have constructed manually below (a list of users with their corresponding scores)

I would be interested in the most efficient way to construct a for loop to achieve this with a list. Note: I am aware that the best way to approach this would be a dictionary, but these purposes I want to use a list.

Code:

biology_score="user1,30,user2,60,user3,99"
print(biology_score[1]) #for testing purposes
b=biology_score.split(",")
print(b) #prints lists
print(b[2]) #prints element in index 2 in the list

#desired output
print(b[0],"scored",b[1])
print(b[2],"scored",b[3])
print(b[4],"scored",b[5])

#create a for loop to do the above

Required answer

  1. The most elegant solution (for loop to produce the above by looping through the list)

  2. The easiest/quickest method to convert the string to a dictionary, using the least number of steps, and then achieving the same output (user: score)

like image 554
Compoot Avatar asked Dec 03 '25 13:12

Compoot


1 Answers

I'm not sure if this is what you're looking for:

biology_score="user1,30,user2,60,user3,99"
print(biology_score[1]) #for testing purposes
b=biology_score.split(",")
biology_dict = {}

for i in range(0, len(b), 2):  #looks only at even indices
    print(b[i],"scored",b[i+1])
    biology_dict[b[i]] = b[i+1]
like image 189
chngzm Avatar answered Dec 06 '25 05:12

chngzm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!