Given:
xs = ['1', '2', '3']
Use map then list to obtain a list of integers:
list(map(int, xs))
In Python 2, list was unnecessary since map returned a list:
map(int, xs)
Answer from cheeken on Stack OverflowGiven:
xs = ['1', '2', '3']
Use map then list to obtain a list of integers:
list(map(int, xs))
In Python 2, list was unnecessary since map returned a list:
map(int, xs)
Use a list comprehension on the list xs:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]
numbers = input("Please type some numbers: ").split()for n in range(0, len(numbers)):numbers[n] = int(numbers[n])
Just tried converting a string list to an int list using a for loop and made this code but not sure what it means step by step, if someone could please explain the last 2 lines it would be much appreciated. Thanks!
Converting string in a list to integers
python - converting list of string to list of integer - Stack Overflow
python - How to convert a string list to an int list? - Stack Overflow
Convert string list of lists to integer in python - Stack Overflow
Hi Everyone,
I'm completely new to python and am completing the Python for Everybody specialisation on Coursera. I am trying to convert strings in a list to integers but my code isn't working. I did manage to get it done with list comprehension but was confused as to why this isn't working. My code is below:
x = ['1','2','3','4'] #create list of numbers as strings
for i in x:
i = int(i) #iterate through each entry in the list and convert it to int from str
print(x)The output I'm getting from this is still:
['1', '2', '3', '4']
Thanks for all the help!
map() is your friend, it applies the function given as first argument to all items in the list.
map(int, yourlist)
since it maps every iterable, you can even do:
map(int, input("Enter the unfriendly numbers: "))
which (in python3.x) returns a map object, which can be converted to a list.
I assume you are on python3, since you used input, not raw_input.
One way is to use list comprehensions:
intlist = [int(x) for x in stringlist]
This should help you:
lst = [['1 2 3'], ['4 5 6'],['7 8 9']]
lst = [elem.split(' ') for lstt in lst for elem in lstt]
lst = [[int(num) for num in lstt[:]] for lstt in lst]
Output:
>>> lst
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
raw = [['1 2 3'], ['4 5 6'], ['7 8 9']]
data = [[int(i) for i in x[0].split(' ')] for x in raw]