[英]How to get sorted (x, y) coordinates by x from a file
所以我的文件看起来像这样。
2,3
44,13
3,4
我的代码看起来像这样。
x = []
y = []
with open('example.txt','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(int(row[1]))
我需要坐标来加载这样的:
2,3
3,4
44,13
我怎样才能实现它? 我试过这样的东西,但它不起作用:(
x = []
y = []
with open('test.txt','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
for row in sorted(plots, key=itemgetter(0)):
x.append(int(row[0]))
y.append(int(row[1]))
您可以将它们zip
在一起,然后使用sorted
:
coordinates = sorted(zip(x, y))
如果您需要解压回x, y
您可以再次使用zip
:
x, y = zip(*coordinates)
我对接受的答案中建议的不断压缩/解压缩感到困惑,这完全没有必要。
import csv
with open('../resources/temp_in.csv', newline='') as in_file:
reader = csv.reader(in_file)
sorted_data = sorted((int(v_1), int(v_2)) for v_1, v_2 in reader)
with open('../resources/temp_in.csv', 'w', newline='') as out_file:
writer = csv.writer(out_file)
writer.writerows(sorted_data)
请注意,我两次打开/关闭同一个文件。 可以只这样做一次,但我发现这更通用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.