如果我有一个包含两列的文件(file.txt或file.dat)(比如说x和y):
x y
1467153 12309
1466231 21300
. .
. .
1478821 10230
我想用x作为键值按升序对每个(x,y)进行排序。如何在python中完成这个?
答案 0 :(得分:3)
Python具有内置函数sorted
,您可以使用它来对列表进行排序。
data = """1467153 12309
1466231 21300
1478821 10230
"""
l = sorted([list(map(int, line.split())) # convert each pair to integers
for line # iterate over lines in input
in data.split("\n") # split on linebreaks
if line], # ignore empty lines
key=lambda x: x[0]) # sort by firt element of pair
print(l)
输出:
[[1466231, 21300], [1467153, 12309], [1478821, 10230]]
编辑:如果您的输入是两个整数列表,请执行以下操作:
xs = [1467153, 1466231, 1478821]
ys = [12309, 21300, 10230]
l = sorted(zip(xs, ys), key=lambda x: x[0])
print(l)
输出:
[(1466231, 21300), (1467153, 12309), (1478821, 10230)]