Issue
I have a txt file with integers, some seperated by spaces and some seperated by comma's.
it looks like this:
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
I want to create 2 lists, 1 list with the first csv's and 1 list of sublists with the other lines of integers like this:
list_1 = [7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1]
list_2 = [[22, 13, 17, 11, 0], [8, 2, 23, 4, 24], [21, 9, 14, 16, 7], [6, 10, 3, 18, 5]]
I cant quite get the result im looking for, anyone that can help me out?
I've tried different ways of loading them in but I always get errors because of the different seperators:
b=[[int(x) for x in i.split()] for i in open("file", "r").readlines()]
can't read the comma separated values for instance
Solution
Try:
list_1 = []
list_2 = []
with open("your_file.txt", "r") as f_in:
for line in map(str.strip, f_in):
if line == "":
continue
if "," in line:
list_1.extend(map(int, line.split(",")))
else:
list_2.append(list(map(int, line.split())))
print(f"{list_1=}")
print(f"{list_2=}")
Prints:
list_1=[7, 4, 9, 5, 11, 17, 23, 2, 0, 14, 21, 24, 10, 16, 13, 6, 15, 25, 12, 22, 18, 20, 8, 19, 3, 26, 1]
list_2=[[22, 13, 17, 11, 0], [8, 2, 23, 4, 24], [21, 9, 14, 16, 7], [6, 10, 3, 18, 5]]
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.