Python Ternary Operator Without else

后端 未结 7 845
执笔经年
执笔经年 2020-11-29 00:36

Is it possible to do this on one line in Python?

if :
    myList.append(\'myString\')

I have tried the ternary operator:

7条回答
  •  既然无缘
    2020-11-29 01:11

    i’d just do this if i wanna add optional elements to a list based on a condition.

    nums = [
            1,
            2,
            3 if  else None,
            4,
           ]
    nums = [i for i in nums if i is not None]
    

    this just replaces the value with None if the condition is not met and then later, it just redefines the list without the None Values. this way they preserve their index if the condition is met

提交回复
热议问题