gpt4 book ai didi

python - 使用相应的行对 Python 列进行排序

转载 作者:太空狗 更新时间:2023-10-30 02:54:36 25 4
gpt4 key购买 nike

我想根据充满 int 的行对列值进行排序:

cart = [[1, 3, 0, 2], ['olives', 'tomatoes', 'avocado', 'patato']]

还有这个

new_cart= [[0, 1, 2, 3], ['avocado', 'olives', 'patato', 'tomatoes' ]]

换句话说,我希望字符串按它们对应的整数值排序:

我发现了这些问题,但没有一个符合我的要求:

how to sort 2d array by row in python?

How to sort multidimensional array by column?

最佳答案

一个 zip-sort-unzip 程序应该可以解决这个问题:

data = [[1, 3, 0, 2], ['olives', 'tomatoes', 'avocado', 'patato']]
sorted_data = zip(*sorted(zip(data[0], data[1])))
# [(0, 1, 2, 3), ('avocado', 'olives', 'patato', 'tomatoes')]

或者如果您想将它们保存为列表:

sorted_data = map(list, zip(*sorted(zip(data[0], data[1]))))
# [[0, 1, 2, 3], ['avocado', 'olives', 'patato', 'tomatoes']]

在 Python 3.x 上,zipmap 都返回迭代器,所以如果你想将它们“烘焙”到列表中,只需按原样“转换”它们,即:

sorted_data = list(map(list, zip(*sorted(zip(data[0], data[1])))))

注意:正如 JJoao 所建议的,您也可以在内部 zip 中使用参数扩展,而不是从列表中明确选择要zip 的字段,例如:

sorted_data = list(map(list, zip(*sorted(zip(*data)))))

关于python - 使用相应的行对 Python 列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45254493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com