【问题标题】:Python sort lists with lists insidePython排序列表,里面有列表
【发布时间】:2013-04-21 20:51:40
【问题描述】:

假设一个列表列表,如下所示:

lists=[[3,2,1,4],[6,4,2,8],[9,6,3,12]]

如果我想按lists[0]排序,应该这样排序:

lists=[[1,2,3,4],[2,4,6,8],[3,6,9,12]] #can be another variable

有一个包含三个列表的列表:

list1,list2,list3=(list(t) for t in zip(*sorted(zip(lists[0], lists[1],lists[2]))))

但这是一个特定的解决方案,列表中的 n 个列表可能更通用。
lists 变量是这样创建的:

lists = [[] for x in xrange(n)]

并且这些值被附加在上面。

实际上所有值都是数字(float 或 int),但这可能更好地解释它。

lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]

我想知道如何排序并最终得到这个:

[[1,2,3,4],["one","two","three","four"],["uno","dos","tres","cuatro"]]

【问题讨论】:

  • 在列表列表中使用* 表示法:zip(*lists)

标签: python list sorting python-2.7


【解决方案1】:

这可能是最好使用 Schwartzian 变换的不太可能的情况

>>> lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]
>>> [[x for i, x in sorted(zip(lists[0], sublist))] for sublist in lists]
[[1, 2, 3, 4], ['one', 'two', 'three', 'four'], ['uno', 'dos', 'tres', 'cuatro']]

【讨论】:

  • 谢谢,这正是我想要的。
猜你喜欢
  • 2010-11-09
  • 1970-01-01
  • 2016-03-15
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
相关资源
最近更新 更多