python - 使用python3从风格为列表和元组的txt文件中获取信息

标签 python list python-3.x tuples

我有一个文件“test.txt”。其数据格式如下:

[(5.0, 1.12, 1, ((False, []), 0.85)), (4.21, 3.2, 2, ((True, []), 0.7997))]\n

此示例仅显示文件中的第一行,该文件实际上有 20 行。

在每一行中,它以“[”开头并以“]”结尾(请注意,“\n”只是一个换行符。)。 如您所见,每行中的模式为“[( (( ) ) ), ( (( ) ) ), ...]”。实际情况下,一个“[ ]”内有 10000 个“( (( ) ) )”。

你知道如何使用python3读取这些信息吗?

我想要的结果是

x_row1 = [[5.0, 1.12, 1],
          [4.21, 3.2, 2],
          ...,
         ]  # len(x_row1) == 10000
y_row1 = [[False, []], 0.85],
          [True, []], 0.7997],
          ...,
         ]  # len(y_row1) == 10000

x_row_all = [[x_row1], [x_row2], ..., [x_row20]]
y_row_all = [[y_row1], [y_row2], ..., [y_row20]]

谢谢。

最佳答案

使用ast.literal_eval :

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

>>> import ast
>>> ast.literal_eval('[(5.0, 1.12, 1, ((False, []), 0.85)), (4.21, 3.2, 2, ((True, []), 0.7997))]\n')
[(5.0, 1.12, 1, ((False, []), 0.85)), (4.21, 3.2, 2, ((True, []), 0.7997))]

对于您的具体问题:

import ast

with open('test.txt', 'r') as f:
    all_rows = list(map(ast.literal_eval, f))

x_row_all = [[item[:3] for item in row] for row in all_rows]
y_row_all = [[item[-1] for item in row] for row in all_rows]

如果您确实需要将元组变成列表,请改为:

def detuple(tup):
    return [detuple(x) if isinstance(x, tuple) else x for x in tup]

x_row_all = [[list(item[:3]) for item in row] for row in all_rows]
# tup = ((False, []), 0.85); detuple(tup) => [[False, []], 0.85]
y_row_all = [[detuple(item[-1]) for item in row] for row in all_rows]

或者,如果您将 all_rows 创建为:

,您也可以从头开始就有列表
all_rows = [ast.literal_eval(line.replace('(', '[').replace(')', ']') for line in f]

关于python - 使用python3从风格为列表和元组的txt文件中获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41877260/

相关文章:

Python subprocess.Popen 管道 IO 意外阻塞

Python从文本文件中提取字符串

python - PyPlot - 在 GUI 中向绘图添加轴标签和标题时遇到困难

python - 在Python中通过ssh读取值

python - python中的实例

list - 如何使用随机选择对 Haskell 中的列表进行洗牌

python - 如何将pandas数据框中的列中具有不同值的行组合起来

python - 写入后中止缓慢刷新到磁盘?

jquery - 当所有列表项都隐藏时隐藏整个列表

list - Haskell: `reverse` 或 right `cons` ,效率更高