题目
code
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
result = collections.defaultdict(list)
for word in strs:
count = [0] *26
for c in word:
count[ord(c) - ord('a')] +=1
result[tuple(count)].append(word)
return list(result.values())
FBI Warning
In python2 , dict.values() return a copy of the dict list;
However, in python3, dict.values() return view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
As a result, you need to encapsulate it into list by list().
details
line 7
defaultdict is a subclass of dict;
defaultdict has default value for the keys (for dict, you the key-value doesn’t exist, throw Keyerror!). You specify the default value by giving a default_factory( it defaults to None. )
The factory may be function or lambda.
line 12
The key of a dict must be invariable object.
List is a variable object, unsuitable for key, OK with tuple.
不可变对象,该对象所指向的内存中的值不能被改变。当改变某个变量时候,由于其所指的值不能被改变,相当于把原来的值复制一份后再改变,这会开辟一个新的地址,变量再指向这个新的地址。
可变对象,该对象所指向的内存中的值可以被改变。变量(准确的说是引用)改变后,实际上是其所指的值直接发生改变,并没有发生复制行为,也没有开辟新的出地址,通俗点说就是原地改变。
Python中,数值类型(int和float)、字符串str、元组tuple都是不可变类型。而列表list、字典dict、集合set是可变类型。