python3 列表和字典的递推

python3 列表和字典的递推,第1张

# 生成准备数据
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')}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/570918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存