python if else语句转换为带有枚举解析列表?

mrwjdhj3  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(101)

Using if-else statements in comprehension lists like this is great:

a = [1, 0, 1, 0, 1, 0, 1, 0, 1]

b = [i-1 if i > 0 else i+1 for i in a]

b
[0, 1, 0, 1, 0, 1, 0, 1, 0]

also using the enumerations makes possible to use the iterator like:

c = [j for j, item in enumerate(b) if item > 0 ]
c
[1, 3, 5, 7]

but how to add an else statement to a comprehension list with enumeration? i.e. something like

c = [j for j, item in enumerate(b) if item > 0 ELSE ]
fcg9iug3

fcg9iug31#

只是重新整理,如

c = [j if item>0 else 99 for j, item in enumerate(b)]

产生

[99, 1, 99, 3, 99, 5, 99, 7, 99]

相关问题