Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对表(列表列表)中的列进行排序,同时保留行的对应关系_Python_List_Sorting - Fatal编程技术网

Python 对表(列表列表)中的列进行排序,同时保留行的对应关系

Python 对表(列表列表)中的列进行排序,同时保留行的对应关系,python,list,sorting,Python,List,Sorting,例如: list1 = ['c', 'b', 'a'] list2 = [3, 2, 1] list3 = ['11', '10', '01'] table = [list1, list2, list3] 我希望根据第一列(列表1)进行排序,但我希望最终的排序仍然保留行(因此在排序之后,我仍然有一行'b',2',10')。在这个例子中,我可以单独对每个列表进行排序,但用我的数据我不能这样做。什么是pythonic方法?一种快速方法是使用zip: >>> from operat

例如:

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

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

一种快速方法是使用
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')]
有关Python如何对元组列表进行排序的信息,请参见。

在使用
sorted
时,这里有一行代码:
table=zip(*sorted(zip(*table),key=itemgetter(0))
# 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]