Aug-24-2022, 04:57 PM
(Aug-23-2022, 05:05 PM)deanhystad Wrote: Why would "marks" be strings when you want them to be int? Should the change be upstream?
If you do have a list of str and you want to convert it to a list of int, you might need check for errors. Depending on what action you need to take when converting the str to an int raises a Value error, map() and list comprehensions might not be an option. You may have no other option than looping through the values.
mport numpy as np marks = ["50", "60.25", "70.75", "spam", "9.25E2"] for index, mark in enumerate(marks): try: value = int(mark) except ValueError: # Cannot convert mark from str to int. Try converting # to float and rounding. try: value = round(float(mark)) except ValueError: # mark cannot be converted to a number value = np.NaN marks[index] = value print(marks)The code converts everything it can to an int, but this would be the wrong place to do the conversion. The correct place to do the conversion is where the data is received. If "marks" is entered using input(), the input strings should be immediately converted to int. If the conversion fails, the user should be prompted to enter correct values.
Output:[50, 60, 71, nan, 925]
If the input is received from another system (web scraping, database query, API call), the conversion should happen immediately, and invalid data reported (logging, error trace). It is a lot easier to track down errors if they are reported when they occur instead of when they cause the program to crash.
I'm sorry, I forgot to mention that I used the input() funtion