【问题标题】:Sorted working differently with '&' in one of the list elements在列表元素之一中使用“&”以不同方式排序
【发布时间】:2018-12-01 05:18:11
【问题描述】:

如果我们有一个字典并转换它

a={'pop': 1, 'Christmas': 1, 'R&B': 2}

然后我们使用排序

sorted(list(a))

为什么会返回这个?:

['Christmas', 'R&B', 'pop']

【问题讨论】:

  • 因为大写字母排在小写之前。

标签: python sorting dictionary


【解决方案1】:
>>> a={'pop': 1, 'Christmas': 1, 'R&B': 2}
>>> list(a)
['pop', 'Christmas', 'R&B']

list(a) 是字典中的键,sorted() 对键进行排序。

【讨论】:

  • 抱歉,您误会了
【解决方案2】:

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']

【讨论】:

  • 知道了,默认情况下就是这样
  • 很高兴,我能帮上忙。如果您觉得有帮助,请按答案左侧的勾号,以便其他有相同疑问的人可以找到有用的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
  • 2011-01-26
  • 2017-03-06
  • 1970-01-01
相关资源
最近更新 更多