How to split numbers in a file by lines, and assign the lines into new lists?
For example,
(numbers below are in a file)
2 56 39 4
20 59 30 68 4
28 50 7 68 95 05 68
I want to make it
List1=[2, 56, 39, 4]
List2=[20, 59, 30, 68, 4]
List3=[28, 50, 7, 68, 95, 05, 68 ]
This is untested, but you would do something similar to the following.
list = []
with open(filename, 'r') as f:
for line in f:
list.append(line.split(" ")) # Split the space-delimited line into a list and add the list to our master list
Remember that list
is now a list of lists of string elements representing the numbers on each line. You'll have to do type conversion when accessing these elements to get an actual number (use something like int(list[list_index][number_index])
).
try:
result = []
with open(filename) as f:
for line in f:
result.append(map(int, line.strip().split()))
print(result)
Output:
[[2, 56, 39, 4], [20, 59, 30, 68, 4], [28, 50, 7, 68, 95, 5, 68]]
You didn't mention if you cared that the output will remains a string, so this is the easiest IMO:
with open('filename') as file:
lines = [row.split() for row in f.read()]
This is tested:
with open('source.txt') as source:
lines = [line.split() for line in source.readlines()]
Output:
[['2', '56', '39', '4'], ['20', '59', '30', '68', '4'], ['28', '50', '7', '68', '95', '05', '68']]
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.