RFC: For Loop Invariants

Vincent Vande Vyvre vincent.vande.vyvre at telenet.be
Mon Apr 20 10:56:37 EDT 2020


Le 20/04/20 à 13:08, Tony Flury via Python-list a écrit :
>
> On 10/04/2020 21:44, Elliott Dehnbostel wrote:
>> *We could do this:*
>>
>> chars = "abcaaabkjzhbjacvb"
>> seek = {'a','b','c'}
>> count = sum([1 for a in chars if a in seek])
>>
>> However, this changes important semantics by creating an entire new
>> list before summing.
>
> Creating the list is pointless in this case - sum will take any
> iterable, including a generator expression:
>
> chars = "abcaaabkjzhbjacvb"
> seek = {'a','b','c'}
> count = sum(1 for a in chars if a in seek)
>
> So you haven't really changed any semantics - and it seems that this
> is far better than fiddling with the for loop syntax.

You can use boolean as integer.

>>> chars = "abcaaabkjzhbjacvb"
>>> seek = {'a', 'b', 'c'}
>>> count = 0
>>> for i in chars:
...     count += i in seek
...
>>> count
11


Vincent.



More information about the Python-list mailing list