List comprehension with condition
问题 I have a simple list. >>> a = [0, 1, 2] I want to make a new list from it using a list comprehension. >>> b = [x*2 for x in a] >>> b [0, 2, 4] Pretty simple, but what if I want to operate only over nonzero elements? 'if' needs 'else' in list comprehensions, so I came up with this. >>> b = [x*2 if x != 0 else None for x in a] >>> b [None, 2, 4] But the desirable result is. >>> b [2, 4] I can do that this way >>> a = [0, 1, 2] >>> def f(arg): ... for x in arg: ... if x != 0: ... yield x*2 ... >