Multiple IF conditions in a python list comprehension

后端 未结 3 1180
再見小時候
再見小時候 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:10

    How about

    ar = [('four' if i % 4 == 0 else ('six' if i % 6 == 0 else i)) for i in range(1, n)]
    

    For example, if n = 30 this is

    [1, 2, 3, 'four', 5, 'six', 7, 'four', 9, 10, 11, 'four', 13, 14, 15, 'four', 17, 'six', 19, 'four', 21, 22, 23, 'four', 25, 26, 27, 'four', 29]
    

    ETA: Here's how you could apply a list of conditions:

    CONDITIONS = [(lambda i: i % 4 == 0, "four"), (lambda i: i % 6 == 0, "six"),
                  (lambda i: i % 7 == 0, "seven")]
    
    def apply_conditions(i):
        for condition, replacement in CONDITIONS:
            if condition(i):
                return replacement
        return i
    
    ar = map(apply_conditions, range(0, n))
    
    0 讨论(0)
  • 2020-12-24 03:18
    ar = ["four" if i%4==0 else "six" if i%6==0  else i for i in range(1,30)]
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题