将文件读取为元组的元组列表

Read file as a list of tuples of tuples

我想使用 Python 读取文本文件。我的列表必须是这样的:

    mylist = [((5., 10.), (6.4, 13)),
              ((7., 11.), (5.6, 5.)),
              ((4., 5.67), (3.1, 2.)),
              ((13., 99.), (3.2, 1.1))]

我的文本文件是:

    text file: 5., 10., 6.4, 13.
               7., 11., 5.6, 5.
               4., 5.67, 3.1, 2.
               13., 99., 3.2, 1.1

python代码为:

    with open('test.txt') as f:
      mylist = [tuple((tuple(map(float, i.split(','))))) for i in f]
    print(mylist)

我的结果:

    [(5.0, 10.0, 6.4, 13.0), (7.0, 11.0, 5.6, 5.0), (4.0, 5.67, 3.1, 2.0), (13.0, 99.0, 3.2, 1.1)]

非常感谢

你可以更进一步:

lst = [(5.0, 10.0, 6.4, 13.0), (7.0, 11.0, 5.6, 5.0), (4.0, 5.67, 3.1, 2.0), (13.0, 99.0, 3.2, 1.1)]
lst2 = [(tt[:2],tt[2:]) for tt in lst]

print(lst2)

输出

[((5.0, 10.0), (6.4, 13.0)), ((7.0, 11.0), (5.6, 5.0)), ((4.0, 5.67), (3.1, 2.0)), ((13.0, 99.0), (3.2, 1.1))]

您需要将行拆分为两个单独的元组。将 mylist 更改为此将起作用:

mylist = [tuple([tuple(s[:2]), tuple(s[2:])]) 
    for s in [list(map(float, i.split(",")))
    for i in f]]