# Python中键映射多个值的方法有两种:
# 想保持元素的插入顺序就应该使用列表;
# 想去掉重复元素就使用集合并且不关心元素的顺序问题的话应该使用set
from collections import defaultdict
mapping1 = defaultdict(list)
value = [1, 2, 3]
for v in value:
mapping1['key'].append(v)
print(mapping1) # defaultdict(<class 'list'>, {'key': [1, 2, 3]})
mapping2 = defaultdict(set)
for i in range(0, 3):
mapping2['key'].add(i)
print(mapping2) # defaultdict(<class 'set'>, {'key': {0, 1, 2}})
# # 那么我们该如何遍历defaultdict呢:
for key, value in mapping2.items():
for v in value:
print(v)
defaultdict使用
Comments 0
Sign in to comment and like
← More postsThat’s all for now. Thanks for reading.
No comments yet.