0
我嘗試使用字典的get
方法來避免if-else
結構,但該方法返回一個None
對象,而我想要一個列表。我的代碼:Python,爲字典獲取方法
dic = {}
words = ['foo', 'bar']
for word in words :
long = len(word)
dic[long] = dic.get(long, []).append(word)
我想有(在循環的末尾):
{3:['foo', 'bar']}
但我有:
AttributeError: 'NoneType' object has no attribute 'append'
這意味着get
返回None
對象(默認值)...其中我雖然應該返回一個無效列表,如果該鍵不存在,一個列表填充一些字符串,如果該鍵存在。有任何想法嗎 ?
你可能有一個更容易的時間,如果你只是用['collections.defaultdict'(https://docs.python.org/2.7/library/collections.html#collections.defaultdict)。 – BrenBarn