[英]Read file as a list of tuples of tuples
I want to read a text file using Python.我想使用 Python 读取文本文件。 My list must be like this:
我的清单必须是这样的:
mylist = [((5., 10.), (6.4, 13)),
((7., 11.), (5.6, 5.)),
((4., 5.67), (3.1, 2.)),
((13., 99.), (3.2, 1.1))]
My text file is:我的文本文件是:
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 code is: python代码是:
with open('test.txt') as f:
mylist = [tuple((tuple(map(float, i.split(','))))) for i in f]
print(mylist)
My result:我的结果:
[(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)]
Thank you so much非常感谢
You can go one step further:你可以更进一步:
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)
Output输出
[((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))]
You need to split the lines into two separate tuples.您需要将行拆分为两个单独的元组。 Changing
mylist
to this will work:将
mylist
更改为此将起作用:
mylist = [tuple([tuple(s[:2]), tuple(s[2:])])
for s in [list(map(float, i.split(",")))
for i in f]]
I want to read a text file using Python.我想使用Python读取文本文件。 My list must be like this:
我的清单必须是这样的:
mylist = [((5., 10.), (6.4, 13)),
((7., 11.), (5.6, 5.)),
((4., 5.67), (3.1, 2.)),
((13., 99.), (3.2, 1.1))]
My text file is:我的文本文件是:
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 code is: python代码是:
with open('test.txt') as f:
mylist = [tuple((tuple(map(float, i.split(','))))) for i in f]
print(mylist)
My result:我的结果:
[(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)]
Thank you so much太感谢了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.