当前位置:   article > 正文

python if-else 写在一行_python if else写在一行

python if else写在一行

python 写在一行技巧


python 写在一行是个不太好的习惯,但有时候为了代码优雅、简洁一些,还是有这种需求的

if-else 写在一行的情况

例子,在一个二维列表里,将每个列表中小于 15 的元素找到,大于 15 的元素赋予 None 值

1、 如输入二维列表:[[1,2,3,18,19], [4,5,6,20,21]]

2、 输出:[[1,2,3,None,None], [4,5,6,None, None]]

data = [[1,2,3,18,19], [4,5,6,20,21]]
res = [[t if t < 15 else None for t in inputs if any(inputs)] for inputs in data]
>>> [[1, 2, 3, None, None], [4, 5, 6, None, None]]
  • 1
  • 2
  • 3

展开便是以下代码,还是挺啰嗦的:

data = [[1,2,3,18,19], [4,5,6,20,21]]
for inputs in data:
    temp = []
    if any(inputs):#不为空列表
        for t in inputs:
            if t < 15:
                temp.append(t)
            else:
                temp.append(None)
    res.append(temp)
>>> [[1, 2, 3, None, None], [4, 5, 6, None, None]]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

仅 if 写在一行的情况

此外,若写在一行中只需要if条件,不需要else条件

例如在一个二维列表里,将每个列表中小于 15 的元素找到

1、 如输入二维列表:[[1,2,3,18,19], [4,5,6,20,21]]

2、 输出:[[1,2,3], [4,5,6]]

data = [[1,2,3,18,19], [4,5,6,20,21]]
res = [[t for t in inputs if t < 15 if any(inputs)] for inputs in data]
>>> [[1, 2, 3], [4, 5, 6]]
  • 1
  • 2
  • 3
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/674807
推荐阅读
相关标签
  

闽ICP备14008679号