我有一个文本文件,看起来像:
2.34 5.32 4.3 [1, 6,-5, 112] other stuff
12.11 5.3 1.93 [11, -6, 55, -12] other stuff
也就是说,每一行都有三个浮点数,后面跟着一个列表,列表后面还有一些其他的东西。我想一次读一行,得到三个浮点数和四个不同变量的列表。我可以用获得所有线路
with open("test.txt", "r") as f:
lines = f.read().splitlines()
但我不知道如何遍历这些行,提取浮点数和列表。
for line in lines:
a, b, c, list_of_integers = parse(line) # How can you implement parse?
# do something with a, b, c, list_of_integers
def parse(line):
# ....
您可以使用:
def parse(line):
p1, p2 = line.split('[', 1)
p2 = p2.split(']', 1)[0]
a, b, c = [float(n) for n in p1.strip().split()]
list_of_integers = [int(n) for n in p2.split(',')]
return a, b, c, list_of_integers
with open("test.txt", "r") as fp:
for line in fp:
a, b, c, list_of_integers = parse(line)
print(a, b, c, list_of_integers)
输出:
2.34 5.32 4.3 [1, 6, -5, 112]
12.11 5.3 1.93 [11, -6, 55, -12]