Is there a "straightforward" way to convert a str containing numbers into a list of [x,y] ints?
# from: '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
# to: [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5]]
By the way, the following works, but wouldn't call it straightforward... Also, it can be assumed that the input str has been validated to make sure that it only contains an even number of numbers interleaved by commas.
num_str = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
numpairs_lst = [] # ends up as [[5, 4], [2, 4], [1, 0], ...]
current_num_str = '' # the current num within the str; stop when a comma is found
xy_pair = [] # this is one of the [x,y] pairs -> [5, 4]
for ix,c in enumerate(num_str):
if c == ',':
xy_pair.append(int(current_num_str))
current_num_str = ''
if len(xy_pair) == 2:
numpairs_lst.append(xy_pair)
xy_pair = []
else:
current_num_str += c
# and, take care of last number...
xy_pair.append(int(current_num_str))
numpairs_lst.append(xy_pair)
question from:https://stackoverflow.com/questions/65833670/converting-a-list-of-strings-into-a-nested-list-of-integers