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')]
Asked By: daniel stafford

||

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"))]
Answered By: bitflip
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.

Answered By: Sifat

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]]
Answered By: mozway

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]]
Answered By: PaulS
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.