5]..._python 字典的快捷表达式">
当前位置:   article > 正文

python字典推导式一行if_python-三元表达式、列表字典集合推导式、生成器表达式...

python 字典的快捷表达式

1.三元表达式:

if成立返回左边的值(1),不成立返回右边的值(0)x = "\n"

print(1 if x == "\n" else 0)

Out: 1

2.列表推导式nums = [i for i in range(0, 10)]

print(nums)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

nums = [i for i in range(0, 10) if i > 5]

print(nums)

[6, 7, 8, 9]

nums = [(i, k) for i in range(0, 2) for k in range(1, 4)]

print(nums)

[(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3)]

3.集合推导式

集合和字典一样,把[]换成{}nums = {i for i in range(0, 10)}

print(nums)

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

nums = {i for i in range(0, 10) if i > 5}

print(nums)

{8, 9, 6, 7}

nums = {(i, k) for i in range(0, 2) for k in range(1, 4)}

print(nums)

{(0, 1), (1, 2), (1, 3), (0, 2), (0, 3), (1, 1)}

4.字典推导式nums = {i + 1: i for i in range(0, 10)}

print(nums)

{1: 0, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8, 10: 9}

nums = {i + 1: i for i in range(0, 10) if i > 5}

print(nums)

{7: 6, 8: 7, 9: 8, 10: 9}

5. 生成器表达式

使用括号表示,结果返回一个生成器对象nums = (i for i in range(0, 100))

print(nums)

at 0x10a90af68>

最后更新于 2020-09-07 01:15:30 并被添加「python」标签,已有 89 位童鞋阅读过。

本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处

相关文章

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/207860
推荐阅读
相关标签
  

闽ICP备14008679号