Home > Back-end >  I want to change the data type of a list, how can i do it?
I want to change the data type of a list, how can i do it?

Time:12-12





user_score = 0
counter = 0
scores = []
while user_score != "done":
    print("type 'done' if you're done inputting")
    user_score = input("write ur score here:").lower()
    scores.append(user_score)
    counter  = 1

counter -= 1
scores.pop()
output = 0

print(type(scores[0]))
result = sum(scores)
print(result)

so i want to create a program where i ll input some numbers and get the average. so the problem is i can t sum up the elements in the "score" variable because they are in string type.

CodePudding user response:

Replace result = sum(scores) with result = sum(map(float, scores)).
This will apply float() to every element of scores, converting them into floats before adding them up.

This is probably less pythonic than list comprehension. So the other answer might provide better readability. It will use up less memory though. Not that this will matter in your case.

CodePudding user response:

You can add

scores = [int(x) for x in scores]

at the end of your loop and after the pop to turn the array into ints

CodePudding user response:

Like Nikita's answer says, you can create a new collection of items which have been type-casted using the map function. I recommend taking a look at the documentation to learn more about how it works.

As an alternative, you can use a list comprehension to accomplish the same thing:

scores = [float(score) for score in scores]
result = sum(scores)

It's best practice to use whichever you find more readable.

CodePudding user response:

You need to add only integers to scores so you can use isnumeric to check if a str value is numberic or str and append only if it is numberic.

If you do so, then you do not need to pop the last element from the list.

Also do not forget type-cast the str to int

user_score = 0
counter = 0
scores = []

while user_score != "done":
    print("type 'done' if you're done inputting")
    user_score = input("write ur score here:").lower()
    if user_score.isnumeric():
      scores.append(int(user_score))
      
    counter  = 1

result = sum(scores)
print(result)
  • Related