gpt4 book ai didi

python - 根据不同数量的属性对列表进行动态排序

转载 作者:行者123 更新时间:2023-12-01 05:04:55 28 4
gpt4 key购买 nike

我见过根据固定数字对列表进行排序的解决方案: Sort a list by multiple attributes?

它有一个很好的排序解决方案:s = 排序(s, key = lambda x: (x[1], x[2]))

还有 itemgetter 示例

但是我有不同数量的属性,例如可以有 2 个属性:

example_list = [{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'x': 'd2_sort': 30},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'x': 'd2_sort': 30},
{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'y': 'd2_sort': 35},
{'d1_desc': 'c', 'd1_sort': 3, 'd2_desc': 'z': 'd2_sort': 38},
etc.
]

但也可以是1个或3个或更多。我不能使用像这样的 lambda 函数或 itemgetter。不过,我确实知道执行时的维数(尽管它因情况而异)。所以我做了这个(使用 2 个暗淡示例的参数集):

example_list = [{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'y', 'd2_sort': 35},
{'d1_desc': 'c', 'd1_sort': 3, 'd2_desc': 'z', 'd2_sort': 38},
{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'z', 'd2_sort': 38},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'c', 'd1_sort': 3, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'z', 'd2_sort': 38}
]

def order_get( a , nr):
result = []
for i in range(1, nr+1):
result.append(a.get('d' + str(i) + '_sort'))
return result

example_list.sort(key = lambda x: order_get(x, 2)) # for this example hard set to 2

In [82]: example_list
Out[82]:
[{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'y', 'd2_sort': 35},
{'d1_desc': 'a', 'd1_sort': 1, 'd2_desc': 'z', 'd2_sort': 38},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'b', 'd1_sort': 2, 'd2_desc': 'z', 'd2_sort': 38},
{'d1_desc': 'c', 'd1_sort': 3, 'd2_desc': 'x', 'd2_sort': 30},
{'d1_desc': 'c', 'd1_sort': 3, 'd2_desc': 'z', 'd2_sort': 38}]

但这真的是最好的方法吗?我的意思是 1) Pythonic 和 2) 性能方面?这是一个常见问题吗?

最佳答案

我仍然会使用 itemgetter,因为它更快,而且您创建一次并每次使用:

from operator import itemgetter

def make_getter(nr):
keys = ('d%d_sort' % (n + 1) for n in xrange(nr))
return itemgetter(*keys)

example_list.sort(key=make_getter(2))

创建itemgetter需要时间。如果您必须在多个列表上使用它,因为它总是相同的,请将其存储 get_two = make_getter(2) 并使用 get_two 作为 key 函数。

关于python - 根据不同数量的属性对列表进行动态排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233031/

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