[英]Pythonic way of diffing two arrays
I call two API endpoints and receive the following responses: 我调用两个API端点并收到以下响应:
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? 我可以使用嵌套的for循环来实现这一目标,但是实现这一目标的最Python方式是什么?
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
: 您也可以使用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: 您可以使用collections.Counter
来映射应用名称以有效地键入计数:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.