如何将文本文件转换为 Python 中的列表?

How to convert a textfile into a list in Python?

我想转换这个文本文件:

(516, 440)
(971, 443)
(1186, 439)
(1402, 441)
(1630, 449)
(299, 681)
(518, 684)
(736, 691)
(739, 431)

进入如下所示的列表:

List = [
(516, 440),
(971, 443),
(1186, 439),
(1402, 441),
(1630, 449),
(299, 681),
(518, 684),
(736, 691),
(739, 431)
]

我在这里找到的答案对我不起作用,因为括号 () 中有逗号。有人知道怎么做吗?

在每一行使用literal_eval

from ast import literal_eval

with open('file.txt') as f:
    data = [
        literal_eval(line.rstrip()) for line in f
    ]
    print(data)

结果:

[(516, 440), (971, 443), (1186, 439), (1402, 441), (1630, 449), (299, 681), (518, 684), (736, 691), (739, 431)]