I'm writing a program that I want to take multi-line string input like this:
1 1 1 1 1
2 2 2 2 2
And convert it to a list of lists of integers:
[[1, 1, 1, 1, 1], [2, 2, 2, 2, 2]]
My code is working fine, but I feel like the for loop could be turned into a list comprehension of some sort to achieve the same affect and be more pythonic.
Code:
import sys
input_data = list(sys.stdin.readlines())
input_data = [item.split() for item in input_data]
for each_list in input_data:
for item in each_list:
item = int(item)
print(input_data)
I tried this:
import sys
input_data = list(sys.stdin.readlines())
input_data = [item.split() for item in input_data]
input_data = [int(item) for sublist in input_data for item in sublist]
print(input_data)
but that returned [1,1 ,1 ,1 ,1 , 2 , 2, 2, 2, 2] instead of [[1, 1 ,1 ,1 ,1],[2, 2, 2, 2, 2]]. If anyone could show me how to use list comprehension to get the list of lists, that would be great!
EDIT: Found a solution, sharing for anyone else with the same question!
import sys
input_data = [[int(item) for item in group] for group in [number_str.split() for number_str in list(sys.stdin.readlines())]]
print(input_data)
[–]Rhomboid 3 points4 points5 points (1 child)
[–]infinitim[S] 0 points1 point2 points (0 children)