So I have the following multidimensional list:
[['50 60 70 60'],
['100 90 87 90'],
['30 65 50 50'],
['58 50 74 43']]
Is there anyway I can convert the strings to a list of ints, such as:
[[50, 60, 70, 60],
[100, 90, 87, 90],
[30, 65, 50, 50],
[58, 50, 74, 43]]
You can use a nested list comprehension where in the outer loop, you iterate over the sublists and in the inner loop, you cast each element of the outcome of str.split
to type int
:
out = [[int(x) for x in lst[0].split()] for lst in lsts]
Output:
[[50, 60, 70, 60], [100, 90, 87, 90], [30, 65, 50, 50], [58, 50, 74, 43]]
This is one way to do it:
in_ = [['50 60 70 60'],
['100 90 87 90'],
['30 65 50 50'],
['58 50 74 43']]
out = []
for list_ in in_:
for nums in list_:
buff = []
buf = nums.split(' ')
for num in buf:
buff.append(int(num))
out.append(buff)
buff = []
print(out)
you can try
> np.array[[50, 60, 70, 60],
[100, 90, 87, 90],
[30, 65, 50, 50],
[58, 50, 74, 43]]
which will convert str to array..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.