gpt4 book ai didi

python - 构建字典值列表,按键排序

转载 作者:太空狗 更新时间:2023-10-29 20:16:41 27 4
gpt4 key购买 nike

我有一个看起来像这样的 python 字典:

attributes = {
'size': ['s','m','l'],
'color': ['black', 'orange'],
}

我想获得一个值列表。如果我使用 values(),我会得到这个:

>>> attributes.values()
[['black', 'orange'], ['s', 'm', 'l']]

但是,我希望生成的列表列表按字典键以相反的顺序排序——即,大小然后是颜色,而不是颜色然后是大小。我想要这个:

[['s', 'm', 'l'], ['black', 'orange']]

我不一定事先知道字典键是什么,但我总是知道我想要它们按字母顺序还是倒字母顺序排列。

是否有一些 pythonic 方法可以做到这一点?

我唯一能想到的似乎...不是很像 python:

keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
result.append(attributes[key])

很难从 attributes.values() 到所有这些只是为了对列表进行排序!

最佳答案

这段代码:

keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
result.append(attributes[key])

基本上是发明列表理解的用例:

result = [attributes[key] for key in sorted(attributes.keys(), reverse=True)]

关于python - 构建字典值列表,按键排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36634809/

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