'Python: List in python turn into a specific format
I have this list of numbers in python
['1', '0', '0', '0', '1', '1', '4']
And I want to turn it into this format (tuple of int).
(1, 0, 0, 0, 1, 1, 4)
How can I do it?
Solution 1:[1]
You could use map
:
>>> nums_list = ['1', '0', '0', '0', '1', '1', '4']
>>> nums_tuple = tuple(map(int, nums_list))
>>> nums_tuple
(1, 0, 0, 0, 1, 1, 4)
Or a comprehension:
>>> nums_tuple = tuple(int(x) for x in nums_list)
>>> nums_tuple
(1, 0, 0, 0, 1, 1, 4)
Solution 2:[2]
You could use list comprehension:
nums_list = ['1', '0', '0', '0', '1', '1', '4']
nums_tuple = tuple([int(x) for x in nums_list])
print(nums_tuple) # (1, 0, 0, 0, 1, 1, 4)
Solution 3:[3]
you can use the method below
nums_list = ['1', '0', '0', '0', '1', '1', '4']
nums_tuple = tuple(int(x) for x in nums_list)
print(nums_tuple)
Solution 4:[4]
change list to numpy array of numbers, and store it my_list = ['1', '0', '0', '0', '1', '1', '4'] my_array = (np.array(my_list,dtype=int))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Vincent |
Solution 3 | ljmc |
Solution 4 | Whereismywall |