Multiple IF conditions in a python list comprehension

后端 未结 3 1184
再見小時候
再見小時候 2020-12-24 02:24

I was wondering, is it possible to put multiple if conditions in a list comprehension? I didn\'t find anything like this in the docs.

I want to be able

3条回答
  •  感动是毒
    2020-12-24 03:20

    You can put you logic in a separate function, and then have the elegance of the list comprehension along with the readability of the function:

    def cond(i):
        if i % 4 == 0: return 'four'
        elif i % 6 == 0: return 'six'
    
        return i
    
    l=[cond(i) for i in range(1,n)]
    

提交回复
热议问题