Python, dictionary列表排序

2024-06-16 11:07:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在整理字典键/值时遇到困难。基本上,这就是我想要达到的目标:(这是有效的)

>>> dict = {}
>>> dict['pens'] = ['234sdf, gjjhj', 'asd123, fghtert', '652efg, vbn456h']
>>> dict['pens'] = sorted(dict['pens'])
>>> print('Sorted: ', dict['pens'])
Sorted:  ['234sdf, gjjhj', '652efg, vbn456h', 'asd123, fghtert']

现在在我的实际脚本中,我得到一个错误:

>>> grpProfile['students'] = sorted(grpProfile['students'])
TypeError: unorderable types: NoneType() < NoneType()
type(grpProfile['students']) # returns list
type(grpProfile['students'][0] )# returns string

这也会显示字符串列表。你知道吗

for s in grpProfile['students']:
  print(s)

我的代码有什么问题?我完全迷路了。我做的每一个测试都是有效的。你知道吗


Tags: type整理dictreturnssortedprintstudentsnonetype
1条回答
网友
1楼 · 发布于 2024-06-16 11:07:12

正如ajcr正确指出的,似乎列表中至少有一个元素是NoneType()类型,即您有一个None对象(可能是您没有设置的变量)。你知道吗

去掉它们,然后对值列表进行排序。要创建不包含该类型实例的列表,请执行以下操作:

[x for x in list if x is not None]

相关问题 更多 >