data = https://www.it610.com/article/[
("animal", "bear"),
("animal", "duck"),
("plant", "cactus"),
("vehicle", "speed boat"),
("vehicle", "school bus")
]
groups = {}
for (key, value) in data:
groups.setdefault(key, []).append(value)
用defaultdict初始化字典对象
from collections import defaultdictgroups = defaultdict(list)
for (key, value) in data:
# 当key不存在于字典中时,list函数将被调用并返回一个空列表赋值给d[key]
groups[key].append(value)
用fromkeys将列表转换成字典
keys = {'a', 'e', 'i', 'o', 'u' }
value = https://www.it610.com/article/[]
d = dict.fromkeys(keys, value)
print(d)
def key_value_gen(k):
yield chr(k+65)
yield chr((k+13)%26+65)
d = dict(map(key_value_gen, range(26)))
iter()可接收callable参数
def random_num():
return randint(0,10)
# iter第一个参数必须是可调用的对象,用于不断调用,产出各个值
# 第二个值是哨符,这是个标记值,当可调用的对象返回这个值时, 触发迭代器抛出StopIteration异常,而不产出哨符
num = iter(random_num, 0)
for i in num:
print(i)