Reputation: 261
I want to read a text file using 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:
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
Upvotes: 1
Views: 140
Reputation: 1163
You need to split the lines into two separate tuples. Changing mylist
to this will work:
mylist = [tuple([tuple(s[:2]), tuple(s[2:])])
for s in [list(map(float, i.split(",")))
for i in f]]
Upvotes: 1
Reputation: 11342
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))]
Upvotes: 1