首页 > 解决方案 > 从存储在文件中的列表格式的字符串创建 Python 中的数字列表

问题描述

我有一个文件,其中包含一个数字列表,其格式与 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) 

我想知道如何从文件中获取它并生成与 Python 中的数字完全相同的列表。

标签: pythonstringlistfilenumbers

解决方案


试试下面的代码。我假设我在一个名为data.txt的文件中有这个问题中的给定数据项。

数据.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) 

数据.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);

参考: 将列表的字符串表示形式转换为实际的列表对象


推荐阅读