[英]Python, sorting a dictionary list
我在整理字典鍵/值時遇到麻煩。 基本上,這就是我要實現的目標:(這可行)
>>> 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)
我的代碼有什么問題? 我完全迷路了。 我所做的每項測試都有效。
正如ajcr正確指出的那樣,列表中似乎至少有一個元素是NoneType()
類型,即您有一個None
對象(可能是尚未設置的變量)。
擺脫它們,然后對值列表進行排序。 要創建沒有該類型實例的列表:
[x for x in list if x is not None]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.