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]
java - Convert List<String> to List<Integer> directly - Stack Overflow
How to convert string list to int list?
Converting string in a list to integers
Convert string list of lists to integer in python - Stack Overflow
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!
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!
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]