I have a file that contains a list of numbers in a format exactly how Python would print it. It is a complex list and in the file it looks like this:
我有一个文件,其中包含一个数字列表,其格式与Python打印的格式完全相同。这是一个复杂的列表,在文件中它看起来像这样:
([(515.51, 615.76), (42.28, 152.3), (223.29, 138.07)], 1)
([(382.27, 502.27), (323.54, 473.01), (212.32, 433.57)], 2)
([(188.74, 442.8), (245.7, 461.47), (391.02, 508.96)], 3)
I would like to know how to get it from the file and generate exactly the same list as numbers in Python.
我想知道如何从文件中获取它并生成与Python中的数字完全相同的列表。
1 个解决方案
#1
0
Try the below code. I am assuming that I have the given data items in this question in a file called data.txt.
请尝试以下代码。我假设我在这个问题中有一个名为data.txt的文件中的给定数据项。
data.txt
([(515.51, 615.76), (42.28, 152.3), (223.29, 138.07)], 1)
([(382.27, 502.27), (323.54, 473.01), (212.32, 433.57)], 2)
([(188.74, 442.8), (245.7, 461.47), (391.02, 508.96)], 3)
data.py
lists = [];
integers = []
with open("data.txt") as f:
for line in f.readlines():
# Each line of file is a tuple with 2 items, first one is list, second one in an integer
tuple = eval(line.strip());
# Append each list from each line to lists list
lists.append(tuple[0]);
# Append each integer from each line to integers list
integers.append(tuple[1]);
print(lists);
print(integers);
Reference: Converting a string representation of a list into an actual list object
参考:将列表的字符串表示形式转换为实际的列表对象
#1
0
Try the below code. I am assuming that I have the given data items in this question in a file called data.txt.
请尝试以下代码。我假设我在这个问题中有一个名为data.txt的文件中的给定数据项。
data.txt
([(515.51, 615.76), (42.28, 152.3), (223.29, 138.07)], 1)
([(382.27, 502.27), (323.54, 473.01), (212.32, 433.57)], 2)
([(188.74, 442.8), (245.7, 461.47), (391.02, 508.96)], 3)
data.py
lists = [];
integers = []
with open("data.txt") as f:
for line in f.readlines():
# Each line of file is a tuple with 2 items, first one is list, second one in an integer
tuple = eval(line.strip());
# Append each list from each line to lists list
lists.append(tuple[0]);
# Append each integer from each line to integers list
integers.append(tuple[1]);
print(lists);
print(integers);
Reference: Converting a string representation of a list into an actual list object
参考:将列表的字符串表示形式转换为实际的列表对象