【问题标题】:sorting a list of two columns based on one column python基于一列python对两列列表进行排序
【发布时间】:2015-03-02 09:52:04
【问题描述】:

如果我有一个包含两列(假设 x 和 y)的文件(file.txt 或 file.dat):

   x      y  
1467153  12309  
1466231  21300  
  .        .  
  .        .  
1478821  10230 

我想以 x 作为键值按升序对每个 (x,y) 进行排序。如何在python中准确地做到这一点?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 到目前为止,我在 python 的两个列表中得到了两列。
  • 如果你有 2 个列表,那么你试试这个..,*.com/questions/6618515/…

标签: python list sorting


【解决方案1】:

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)]

【讨论】:

  • Python 很漂亮。
最近更新 更多