user10387539
user10387539

Reputation:

List comprehension with assignments

I'm new to Python and I try to convert this:

for source in data['Source']:
    for index in range(len(source)):
        if source == sources[index]:
            percent[index] += 1
            pass

to this:

sources = [percent[index]+=1 for source in data['Source'] for index in range(len(source)) if source == sources[index]]

but I give an error E0001, after reading Python documentation I don't know how to convert this to a list comprehension.

Upvotes: 0

Views: 385

Answers (1)

blhsing
blhsing

Reputation: 106543

Assignments are statements, which are not allowed in list comprehensions, which support only expressions.

You can use sum instead:

sources = {index: sum(1 for index in range(len(source)) if source == sources[index]) for source in data['Source']}

A more efficient method would be to use collections.Counter, as @Amadan has suggested in the comments:

import collections.Counter:
sources = Counter(index for source in data['Source'] for index in range(len(source)) if source == sources[index])

Upvotes: 2

Related Questions