【问题标题】:Sorting columns in a table (list of lists) whilst preserving the correspondence of the rows对表中的列(列表列表)进行排序,同时保留行的对应关系
【发布时间】:2011-07-01 00:10:41
【问题描述】:

例如:

list1 = ['c', 'b', 'a']
list2 = [3, 2, 1]
list3 = ['11', '10', '01']
table = [list1, list2, list3]

我想对第一列 (list1) 进行排序,但我希望最终的排序仍然保留这些行(所以排序后我仍然有一行 'b', 2, ' 10')。在这个例子中,我可以单独对每个列表进行排序,但使用我的数据我不能这样做。什么是pythonic方法?

【问题讨论】:

    标签: python list sorting


    【解决方案1】:

    一种快速的方法是使用zip

    >>> from operator import itemgetter
    >>> transpose = zip(*table)
    >>> transpose.sort(key=itemgetter(0))
    >>> table = zip(*transpose)
    >>> table
    [('a', 'b', 'c'), (1, 2, 3), ('01', '10', '11')]
    

    【讨论】:

    • FMcsorted 的使用稍作评论,这里是上面的一条线:table = zip(*sorted(zip(*table), key=itemgetter(0)))
    【解决方案2】:
    # Get a list of indexes (js), sorted by the values in list1.
    js = [t[1] for t in sorted((v,i) for i,v in enumerate(list1))]
    
    # Use those indexes to build your new table.
    sorted_table = [[row[j] for j in js] for row in table]
    

    有关 Python 如何对元组列表进行排序的信息,请参阅 this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2016-07-17
      • 2018-11-06
      • 2016-11-03
      • 2012-08-17
      • 1970-01-01
      • 2012-07-07
      相关资源
      最近更新 更多