gpt4 book ai didi

Python - 对字典{String Key : List of Strings} by len(value)?进行排序

转载 作者:行者123 更新时间:2023-11-28 17:47:24 24 4
gpt4 key购买 nike

假设我有以下字典:

{"A":["u","w"],"B":["t"],"C":["x","y","z"]}

如何按每个值列表中的字符串数对字典进行排序,以便它返回:

[("C",["x","y","z"]), ("A",["u","w"]), ("B":["t"])]

因为“C”的值在列表中有三项,“A”有两项,“B”有一项。我在想一些事情:

sorted(d.items(),key=operator.methodcaller(len(),tuple[1]),reverse=True)

或者

sorted(d.items(),key=(string, stringList):(len(stringList),string),reverse=True)

但两者似乎都不起作用。对排序还是很陌生,所以感谢您的帮助!

最佳答案

>>> d = {"A":["u","w"],"B":["t"],"C":["x","y","z"]}
>>> sorted(d.items(), key=lambda x: len(x[1]), reverse=True)
[('C', ['x', 'y', 'z']), ('A', ['u', 'w']), ('B', ['t'])]

关于Python - 对字典{String Key : List of Strings} by len(value)?进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077241/

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