简体   繁体   中英

Pythonic way of diffing two arrays

I call two API endpoints and receive the following responses:

applications = [{'id': '1', 'name': 'app1'}, {'id': '2', 'name': 'app2'}]
types = [{'id': '3', 'name': 'app1'}, {'id': '4', 'name': 'app1'}]

I'm looking for the following output:

app1 has 2 types.
app2 has 0 types.

I could achieve this with nested for loops, but what's the most Pythonic way of achieving this?

types = [app['name'] for app in types]
apps = {app['name']:types.count(app['name']) for app in applications}

The apps dictionary will give you an apps count in types. Is this what you're looking for?

You can also accomplish this with pandas :

import pandas as pd
counts = pd.DataFrame(types).groupby('name').count()
application_names = {x['name'] for x in applications}
{name: counts['id'].get(name, 0) for name in application_names}

You can use collections.Counter to map the app names to type counts efficiently:

from collections import Counter
counts = Counter(type['name'] for type in types)
for app in applications:
    print(f'{app["name"]} has {counts[app["name"]]} types.')

This outputs:

app1 has 2 types.
app2 has 0 types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM