python if else单行,单行列表理解:if-else变体

It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range:

[x for x in range(1, 10) if x % 2]

This makes a filter - I've got a source list, where I remove even numbers (if x % 2). I'd like to use something like if-then-else here. Following code fails:

>>> [x for x in range(1, 10) if x % 2 else x * 100]

File "", line 1

[x for x in range(1, 10) if x % 2 else x * 100]

^

SyntaxError: invalid syntax

There is a python expression like if-else:

1 if 0 is 0 else 3

How to use it inside a list comprehension?

解决方案

x if y else z is the syntax for the expression you're returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a "complex" one, which happens to involve an if-else.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值