【问题标题】:How to read the text-file containing list of lists when the list is like [(81, 134), (176, 134)]当列表类似于 [(81, 134), (176, 134)] 时如何读取包含列表列表的文本文件
【发布时间】:2020-01-01 21:40:03
【问题描述】:

我正在尝试读取包含包含坐标元组的列表列表的文本文件。如何读取文件以获得列表列表?

文本文件的示例内容是,

[(75, 143), (187, 138)]

[(85, 140), (193, 134)]

[(65, 120)]

.

.

.

.

.

我尝试使用以下代码读取文件。它能够读取文件。但它将它作为 str 而不是列表存储在“x”中。如何将其转换为列表?

filename1 = 'testfile.txt'

m_text = open(Filename1,'r+')

m_List = []

with open(Filename1) as mf:

    x = mf.readlines()

【问题讨论】:

标签: python-3.x string list int tuples


【解决方案1】:

根据您的代码输出是这样的,一个列表由字符串表示的列表组成,每个元素末尾带有\n,单个\n

['[(75, 143), (187, 138)]\n', '\n', '[(85, 140), (193, 134)]\n', '\n', '[(65, 120)]\n']

要将其转换为列表,您需要从每个元素中删除 thos \n。并转换回 python 列表。这可以使用lambdamapstripeval 函数和list comprehension 来完成,这是 python 的强大功能。

filename1 = 'testfile.txt'
m_List = []
with open(file=filename1, mode='r', encoding='utf-8') as mf:
    x = mf.readlines()
    m_List = [cordinate for cordinate in list(map(lambda i: eval(str(i).strip()) if str(i).strip() else None, x)) if cordinate]
    print(m_List)

给出输出:

[[(75, 143), (187, 138)], [(85, 140), (193, 134)], [(65, 120)]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多