Reputation: 62
I have data in a text file -->
p6;744951.1924;3553854.3858;246.8029
p1;745673.7331;35106063.9248;357.3721
p10;756311.8836;3546027.3642;922.0692
Now I want to sort the data according to first i.e p6,p1,p10.
I have done some code but I am not getting on how to sort. Please help
id = []
east = []
north = []
height = []
sorted = []
with open("coordinates.txt","r") as file:
for line in file:
data = line.split(";")
id.append(data[0])
east.append(round(float(data[1]),2))
north.append(round(float(data[2]),2))
height.append(round(float(data[3]),2))
for x in id:
# my code here
print(id)
print(east)
print(north)
print(height)
Upvotes: 0
Views: 39
Reputation: 23146
Try:
with open("coordinates.txt") as f:
coordinates = [line.strip().split(";") for line in f.readlines()]
>>> sorted(coordinates, key=lambda x: int(x[0][1:]))
[['p1', '745673.7331', '35106063.9248', '357.3721'],
['p6', '744951.1924', '3553854.3858', '246.8029'],
['p10', '756311.8836', '3546027.3642', '922.0692']]
If you want to do it without lambda, you can save your data to a dictionary instead:
coordinates = dict()
with open("test.txt") as f:
for line in f:
i, n, e, h = line.strip().split(";")
coordinates[int(i[1:])] = (float(n), float(e), float(h))
for key in sorted(coordinates):
print(coordinates[key])
(745673.7331, 35106063.9248, 357.3721)
(744951.1924, 3553854.3858, 246.8029)
(756311.8836, 3546027.3642, 922.0692)
Upvotes: 1
Reputation: 15364
You could do something like this:
id, east, north, height = zip(*sorted(zip(id, east, north, height)))
Result:
>>> id
('p1', 'p10', 'p6')
>>> east
(745673.73, 756311.88, 744951.19)
>>> north
(35106063.92, 3546027.36, 3553854.38)
>>> height
(357.37, 922.06, 246.8)
If you're not happy with alphabetical order:
id, east, north, height = zip(*sorted(zip(id, east, north, height), key=lambda x: int(x[0][1:])))
Result:
>>> id
('p1', 'p6', 'p10')
>>> east
(745673.73, 744951.19, 756311.88)
>>> north
(35106063.92, 3553854.38, 3546027.36)
>>> height
(357.37, 246.8, 922.06)
Upvotes: 0