# 生成准备数据
d = {1: 'a', 2: 'b', 3: 'c'}
# 递推列表
lst1 = [(num, word) for num, word in d.items()]
print(lst1) # [(1, 'a'), (2, 'b'), (3, 'c')]
# 递推字典
dic1 = {num: item for num, item in enumerate(lst1)}
print(dic1) # {0: (1, 'a'), 1: (2, 'b'), 2: (3, 'c')}
print()
# 递推带上判断玩(不支持else)
# 递推列表
lst2 = [(num, word) for num, word in d.items() if num < 3]
print(lst2) # [(1, 'a'), (2, 'b')]
# 递推字典
dic2 = {num: item for num, item in enumerate(lst2) if len(lst2) >= 3}
print(dic2) # {}
print()
# 递推再带上函数玩
def numAdd(x):
x += 1
return x
# 递推列表
lst3 = [(numAdd(num), word) for num, word in d.items() if num < 3]
print(lst3) # [(2, 'a'), (3, 'b')]
# 递推字典
dic3 = {numAdd(num): item for num, item in enumerate(lst1) if len(lst1) >= 3}
print(dic3) # {1: (1, 'a'), 2: (2, 'b'), 3: (3, 'c')}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)