Posts: 10
Threads: 3
Joined: Jul 2022
hi there everyone!
I have a question related to changing the datatype of list:
- How to change the datatype of list?
Posts: 4,784
Threads: 76
Joined: Jan 2018
It is very difficult to understand what you want to do and why you want to do it. Can you explain it with more details?
Posts: 6,779
Threads: 20
Joined: Feb 2020
lists don't have a datatype. Are you thinking arrays? np.arrays and ctypes arrays have types. Python lists can contain objects of different types.
Posts: 2,168
Threads: 35
Joined: Sep 2016
It might be clearer if you give an example of what the list looked like initially and then how the list should look afterwards.
Posts: 10
Threads: 3
Joined: Jul 2022
Aug-23-2022, 03:22 PM
(This post was last modified: Aug-23-2022, 03:26 PM by Yoriz.
Edit Reason: Added code tags
)
example:
>>>> marks=["50","60","70","80","90"] all the elements are in string datatype. I want to change elements into integers.
Posts: 2,168
Threads: 35
Joined: Sep 2016
Aug-23-2022, 03:28 PM
(This post was last modified: Aug-23-2022, 03:28 PM by Yoriz.)
You can loop through the list and make a new list that changes each item into an int.
marks = ["50", "60", "70", "80", "90"]
marks = [int(mark) for mark in marks]
print(marks) Output: [50, 60, 70, 80, 90]
ndc85430 and mHosseinDS86 like this post
Posts: 1,950
Threads: 8
Joined: Jun 2018
Alternative way is to use built-in map function:
>>> marks = ["50", "60", "70", "80", "90"]
>>> list(map(int, marks))
[50, 60, 70, 80, 90]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 6,779
Threads: 20
Joined: Feb 2020
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) Output: [50, 60, 71, nan, 925]
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.
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.
Posts: 10
Threads: 3
Joined: Jul 2022
(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) Output: [50, 60, 71, nan, 925]
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.
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
Posts: 6,779
Threads: 20
Joined: Feb 2020
When using input(), the conversion should happen as soon as the value is entered. Something like this:
def enter_mark(prompt="Enter mark: ", min_=0, max_=100):
while True:
try:
entry = input(prompt)
value = int(entry)
except ValueError:
print(f"{entry} is not an integer value")
else:
if value < min_ or value > max_:
print(f"{value} is not in the range {min_}..{max_}")
else:
break
return value
print([enter_mark() for _ in range(5)])
|