data = [("p", 1), ("p", 2), ("p", 3),
("h", 1), ("h", 2), ("h", 3)]
要转换成
result = {'p': [1, 2, 3], 'h': [1, 2, 3]}
result = {}
for (key, value) in data:
if key in result:
result[key].append(value)
else:
result[key] = [value]
def setdefault(self, k, d=None):
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
value = D.get(k,d)
if k not in D:
D[k]=d
return value
>>> d = {"x":3}
>>> y = d.get("y", 4)
>>> y
4
>>> d
{'x': 3}
>>> y = d.setdefault("y", 4)
>>> y
4
>>> d
{'y': 4, 'x': 3}
result = {}
data = [("p", 1), ("p", 2), ("p", 3),
("h", 1), ("h", 2), ("h", 3)]
for (key, value) in data:
result.setdefault(key, []).append(value)
>>> result = defaultdict(list)
>>> result
defaultdict(<type 'list'>, {})
>>> result['a']
[]
from collections import defaultdict
result = defaultdict(list)
data = [("p", 1), ("p", 2), ("p", 3),
("h", 1), ("h", 2), ("h", 3)]
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |