Python按模板对数组进行排序

2024-05-15 22:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含任意数据的数组,需要对它们进行排序,以便具有特定键(unicorn)的子元素位于末尾:

输入:[[1,2,'dog'], [2,2,'unicorn'], [2,3,'unicorn'], [3,3,'cat']]
输出:[[1,2,'dog'], [3,3,'cat'], [2,2,'unicorn'], [2,3,'unicorn']]

我目前正在通过一次穿过阵列并将单管移动到第二个阵列来实现这一点。。。 如果我需要“移动”多个键,它会变得很难看


Tags: 数据元素排序数组catunicorn末尾dog
2条回答

Python有一个名为^{}的内置函数。这需要一个iterable(例如此列表)和一个可选的键函数。要以所有其他元素的相对位置不变的方式进行排序,可以使用以下方法:

sorted([[1,2,'dog'], [2,2,'unicorn'], [2,3,'unicorn'], [3,3,'cat']],
       key=lambda v: 1 if v[2] == 'unicorn' else 0)
# [[1, 2, 'dog'], [3, 3, 'cat'], [2, 2, 'unicorn'], [2, 3, 'unicorn']]

您可以使用sort函数并为其提供一个键参数,以便根据第三个元素进行排序。 这样,阵列将被“就地”排序

def sorter(el):
    if el[2] == 'unicorn':
        return 1
    return 0

arr = [[1,2,'dog'], [2,2,'unicorn'], [2,3,'unicorn'], [3,3,'cat']]

arr.sort(key=sorter)

使用sorted函数也可以得到相同的结果 这样sorted函数将返回一个新数组

def sorter(el):
    if el[2] == 'unicorn':
        return 1
    return 0

arr = [[1,2,'dog'], [2,2,'unicorn'], [2,3,'unicorn'], [3,3,'cat']]  
sorted_arr = sorted(arr, key=sorter)

相关问题 更多 >