Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python3从一个样式为列表和元组的txt文件中获取信息_Python_List_Python 3.x_Tuples - Fatal编程技术网

使用python3从一个样式为列表和元组的txt文件中获取信息

使用python3从一个样式为列表和元组的txt文件中获取信息,python,list,python-3.x,tuples,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阅读这些信息吗

我有一个文件“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]]
谢谢。

使用:

安全地计算表达式节点或包含Python的字符串 文字或容器显示。提供的字符串或节点只能 由以下Python文本结构组成:字符串、字节、, 数字、元组、列表、dict、set、boolean和
None

针对您的具体问题:

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 = [ast.literal_eval(line.replace('(', '[').replace(')', ']') for line in f]
all_rows = [ast.literal_eval(line.replace('(', '[').replace(')', ']') for line in f]