How to split string based on position in string
Question:
Given the following text:
input_value= """12
23
54"""
I want to return lists with the first and second elements of each line:
[[1,2,5], [2,3,4]]
I am trying to achieve this using a one-liner but struggling to access the correct indexes of each line and then placing them into a separate list. The number of returned lists should be equal to the number of digits present on each line:
I’ve tried the following as a base but clearly requires more logic in order to retrieve the correct digits:
new_list = [[elem] for elem in input_value.split('n')]
Answers:
You could use something like
[[*elems] for elems in zip(*input_value.split("n"))]
EDIT:
To create a list of integers, use
[[*map(int, elems)] for elems in zip(*input_value.split("n"))]
input_value= """12
23
54
"""
lst1 = []
lst2 = []
for i in input_value.splitlines():
if i:
lst1.append(int(i[0]))
lst2.append(int(i[1]))
lst = [lst1, lst2]
print(lst)
See if this works.
Use a nested list comprehension:
out = [[int(i) for i in x] for x in zip(*input_value.split('n'))]
Output:
[[1, 2, 5], [2, 3, 4]]
Another possible solution:
[[list(map(int,x))[y] for x in input_value.split()] for y in range(2)]
Output:
[[1, 2, 5], [2, 3, 4]]
Given the following text:
input_value= """12
23
54"""
I want to return lists with the first and second elements of each line:
[[1,2,5], [2,3,4]]
I am trying to achieve this using a one-liner but struggling to access the correct indexes of each line and then placing them into a separate list. The number of returned lists should be equal to the number of digits present on each line:
I’ve tried the following as a base but clearly requires more logic in order to retrieve the correct digits:
new_list = [[elem] for elem in input_value.split('n')]
You could use something like
[[*elems] for elems in zip(*input_value.split("n"))]
EDIT:
To create a list of integers, use
[[*map(int, elems)] for elems in zip(*input_value.split("n"))]
input_value= """12
23
54
"""
lst1 = []
lst2 = []
for i in input_value.splitlines():
if i:
lst1.append(int(i[0]))
lst2.append(int(i[1]))
lst = [lst1, lst2]
print(lst)
See if this works.
Use a nested list comprehension:
out = [[int(i) for i in x] for x in zip(*input_value.split('n'))]
Output:
[[1, 2, 5], [2, 3, 4]]
Another possible solution:
[[list(map(int,x))[y] for x in input_value.split()] for y in range(2)]
Output:
[[1, 2, 5], [2, 3, 4]]