【发布时间】:2018-12-01 05:18:11
【问题描述】:
如果我们有一个字典并转换它
a={'pop': 1, 'Christmas': 1, 'R&B': 2}
然后我们使用排序
sorted(list(a))
为什么会返回这个?:
['Christmas', 'R&B', 'pop']
【问题讨论】:
-
因为大写字母排在小写之前。
标签: python sorting dictionary
如果我们有一个字典并转换它
a={'pop': 1, 'Christmas': 1, 'R&B': 2}
然后我们使用排序
sorted(list(a))
为什么会返回这个?:
['Christmas', 'R&B', 'pop']
【问题讨论】:
标签: python sorting dictionary
>>> a={'pop': 1, 'Christmas': 1, 'R&B': 2}
>>> list(a)
['pop', 'Christmas', 'R&B']
list(a) 是字典中的键,sorted() 对键进行排序。
【讨论】:
list(a) 提供字典键列表,sorted 对其进行排序。因为您的键是大写和小写字符的混合,所以您不会期望它以所需的方式返回,因为大写字母在小写之前排序。
处理这种情况的一种方法是定义一个自定义函数,例如:
a = {'pop': 1, 'Christmas': 1, 'R&B': 2}
def lower(x):
return x.lower()
print(sorted(list(a), key=lower))
# ['Christmas', 'pop', 'R&B']
如果您尝试按单词长度排序,可以这样:
a = {'pop': 1, 'Christmas': 1, 'R&B': 2}
print(sorted(list(a), key=len))
# ['pop', 'R&B', 'Christmas']
【讨论】: