generator-expression

List comprehension with condition

扶醉桌前 提交于 2019-12-21 09:19:49
问题 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 ... >

“Tuple comprehensions” and the star splat/unpack operator *

混江龙づ霸主 提交于 2019-12-21 05:36:18
问题 I just read the question Why is there no tuple comprehension in Python? In the comments of the accepted answer, it is stated that there are no true "tuple comprehensions". Instead, our current option is to use a generator expression and pass the resulting generator object to the tuple constructor: tuple(thing for thing in things) Alternatively, we can create a list using a list comprehension and then pass the list to the tuple constructor: tuple([thing for thing in things]) Lastly and to the

Python generator expression parentheses oddity

泄露秘密 提交于 2019-12-20 18:02:14
问题 I want to determine if a list contains a certain string, so I use a generator expression, like so: g = (s for s in myList if s == myString) any(g) Of course I want to inline this, so I do: any((s for s in myList if s == myString)) Then I think it would look nicer with single parens, so I try: any(s for s in myList if s == myString) not really expecting it work. Surprise! it does! So is this legal Python or just something my implementation allows? If it's legal, what is the general rule here?

Python generator expression parentheses oddity

爱⌒轻易说出口 提交于 2019-12-20 18:01:13
问题 I want to determine if a list contains a certain string, so I use a generator expression, like so: g = (s for s in myList if s == myString) any(g) Of course I want to inline this, so I do: any((s for s in myList if s == myString)) Then I think it would look nicer with single parens, so I try: any(s for s in myList if s == myString) not really expecting it work. Surprise! it does! So is this legal Python or just something my implementation allows? If it's legal, what is the general rule here?

Python generator expression parentheses oddity

蹲街弑〆低调 提交于 2019-12-20 18:01:06
问题 I want to determine if a list contains a certain string, so I use a generator expression, like so: g = (s for s in myList if s == myString) any(g) Of course I want to inline this, so I do: any((s for s in myList if s == myString)) Then I think it would look nicer with single parens, so I try: any(s for s in myList if s == myString) not really expecting it work. Surprise! it does! So is this legal Python or just something my implementation allows? If it's legal, what is the general rule here?

Why results of map() and list comprehension are different?

流过昼夜 提交于 2019-12-17 04:32:55
问题 The following test fails: #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__main__': import doctest; doctest.testmod() In other words: >>> t = 1, -1 >>> args = [] >>> for i in t: ... args.append(lambda: i) ... >>> map(lambda a: a(), args) [-1, -1] >>> args = [] >>> for i in t: ..

Python union of sets raises TypeError

五迷三道 提交于 2019-12-12 20:18:10
问题 Consider a sequence of sets: >>> [{n, 2*n} for n in range(5)] [{0}, {1, 2}, {2, 4}, {3, 6}, {8, 4}] Passing them directly into the union method yields the correct result: >>> set().union({0}, {1, 2}, {2, 4}, {3, 6}, {8, 4}) {0, 1, 2, 3, 4, 6, 8} But passing them as a list or generator expression results in a TypeError: >>> set().union( [{n, 2*n} for n in range(5)] ) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set' >>> set().union({n, 2*n

Easy way to change generator into list comprehension without duplicating code in python?

一世执手 提交于 2019-12-12 18:02:25
问题 I have something like this: class TransMach: def __init__(self, machfile, snpfile): self.machfile = machfile self.snpfile = snpfile def __translines(self): fobj = open(self.machfile) lines = (l.strip().split()[2] for l in fobj) tlines = zip(*lines) return tlines Generator is used in order to avoid reading the whole file into memory, but sometimes reading the whole file is exactly what is desirable (i.e. list comprehension). How can I change this kind of behavior without too much extra code?

Reusing generator expressions

放肆的年华 提交于 2019-12-12 13:23:16
问题 Generator expressions is an extremely useful tool, and has a huge advantage over list comprehensions, which is the fact that it does not allocate memory for a new array. The problem I am facing with generator expressions, which eventually makes me end up writing list comprehensions, is that I can only use a such a generator once: >>> names = ['John', 'George', 'Paul', 'Ringo'] >>> has_o = (name for name in names if 'o' in name) >>> for name in has_o: ... print(name.upper()) ... JOHN GEORGE

Why is updating a list faster when using a list comprehension as opposed to a generator expression?

半世苍凉 提交于 2019-12-11 15:08:25
问题 According to this answer lists perform better than generators in a number of cases, for example when used together with str.join (since the algorithm needs to pass over the data twice). In the following example using a list comprehension seems to yield better performance than using a corresponding generator expression though intuitively the list comprehension comes with an overhead of allocating and copying to additional memory which the generator sidesteps. In [1]: l = list(range(2_000_000))