python - 从存储在文件中的列表格式的字符串创建 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 中的数字完全相同的列表。
解决方案
试试下面的代码。我假设我在一个名为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);
推荐阅读
- node.js - HapiJS:根据request中传入的查询参数配置HapiJs API?
- react-native - react-native 改变数组中元素的属性?
- mongodb - MongoDB 排序检查索引列上的太多记录
- browser - 是否可以使用 PAT 浏览到 TFS 网络门户?
- java - 无法解析符号,android studio
- swift - 如何将名称/标题/值(月)添加到折线图的 Y 轴?
- jakarta-ee - @Qualifier 没有考虑不同的持久性单元 - EntityManager Produces
- r - 在R闪亮中显示PDF文件?
- django - 在 Django 数据库中建模“网络”
- react-native - 在 react-native 中创建多个圆形线性加载条