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.

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to