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 ]
1条答案
按热度按时间fcg9iug31#
只是重新整理,如
产生