Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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 3.x 如何根据应用于一个列表的排序对多个Python列表进行排序?_Python 3.x_List_Sorting - Fatal编程技术网

Python 3.x 如何根据应用于一个列表的排序对多个Python列表进行排序?

Python 3.x 如何根据应用于一个列表的排序对多个Python列表进行排序?,python-3.x,list,sorting,Python 3.x,List,Sorting,我有一个Python列表,本质上表示一个表。我知道我应该使用熊猫数据帧来完成这一点,但事后看来是20/20。我离题了…下面是我所说内容的示例列表 总体列表变量由以下嵌套列表组成: ['Store number', 2, 3, 4, 1, 5] ['Variable 1', 82, 99, 44, 32, 65] ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile'] 在当前状态下,每个嵌套列表的每个索引都对应于表中的同一行。

我有一个Python列表,本质上表示一个表。我知道我应该使用熊猫数据帧来完成这一点,但事后看来是20/20。我离题了…下面是我所说内容的示例列表

总体列表变量由以下嵌套列表组成:

['Store number', 2, 3, 4, 1, 5]
['Variable 1', 82, 99, 44, 32, 65]
['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile']
在当前状态下,每个嵌套列表的每个索引都对应于表中的同一行。所以对于存储编号2,变量1是82,字符串1是cat。假设我想将每个列表排序到维护这些关系的位置,但我们按存储编号升序排序。最终的列表如下所示:

['Store number', 1, 2, 3, 4, 5]
['Variable 1', 32, 82, 99, 44, 65]
['String 1', 'alligator', 'cat', 'dog', 'lizard', 'crocodile']

我如何使用当前的数据结构来实现这一点?

如果必须使用当前的数据结构,这里有一个函数可以满足您的需要。请注意,可能有更聪明的方法,但这会起作用

鉴于:

lolists = [['Store number', 2, 3, 4, 1, 5],
            ['Variable 1', 82, 99, 44, 32, 65],
            ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile']      
            ]
def sortinnerLists(lol):
    kys = lol[0][1:]
    sortedKys = sorted(kys)
    rslt = [[lol[0][0]], [lol[1][0]], [lol[2][0]]]
    for v in sortedKys:
        indx = kys.index(v)+1
        rslt[0].append(v)
        rslt[1].append(lol[1][indx])
        rslt[2].append(lol[2][indx])
    return rslt    
sortinnerLists(lolists)  
收益率:

[['Store number', 1, 2, 3, 4, 5],
 ['Variable 1', 32, 82, 99, 44, 65],
 ['String 1', 'alligator', 'cat', 'dog', 'lizard', 'crocodile']]

您可以根据其中一个列表中的值对
范围内的索引列表进行排序。然后可以使用索引对原始的三个列表进行重新排序:

store = ['Store number', 2, 3, 4, 1, 5]
var1 = ['Variable 1', 82, 99, 44, 32, 65]
str1 = ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile']

sort_indexes = sorted(range(1, len(store)), key=lambda i:store[i])

store[1:] = [store[i] for i in sort_indexes]
var1[1:] = [var1[i] for i in sort_indexes]
str1[1:] = [str1[i] for i in sort_indexes]
如果每个列的标题不包含在同一个列表中,那么使用您的数据结构会更好。但这种尴尬实际上并不会对这段代码产生太大影响,因为我们不是直接对列表排序,而是对索引进行排序,从索引
1
开始而不是
0
,这样做并没有什么问题。如果将标题从数据中移出,则只需跳过代码末尾的切片赋值(直接使用列表理解值即可)