【问题标题】:Create list of numbers in Python from list-formatted string stored in file从存储在文件中的列表格式的字符串创建 Python 中的数字列表
【发布时间】:2018-10-29 16:22:49
【问题描述】:

我有一个文件,其中包含一个数字列表,其格式与 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 中的数字完全相同的列表。

【问题讨论】:

    标签: python string list file numbers


    【解决方案1】:

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

    data.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) 
    

    data.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);
    

    参考:Converting a string representation of a list into an actual list object

    【讨论】:

    • 它引发了我“ValueError: No JSON object could be decoded”。
    • 让我检查一下,我在手机上无法编译。我会尽快回复你。谢谢@tzoukritziu
    • @tzoukritziu,你现在可以检查一下吗。
    • 没问题,我错误地用json.loads() 代替了eval()。您还可以查看答案中的参考链接。它会给你eval()的想法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2022-11-16
    • 2016-03-22
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多