[英]Pythonic way of diffing two arrays
我调用两个API端点并收到以下响应:
applications = [{'id': '1', 'name': 'app1'}, {'id': '2', 'name': 'app2'}]
types = [{'id': '3', 'name': 'app1'}, {'id': '4', 'name': 'app1'}]
我正在寻找以下输出:
app1 has 2 types.
app2 has 0 types.
我可以使用嵌套的for循环来实现这一目标,但是实现这一目标的最Python方式是什么?
types = [app['name'] for app in types]
apps = {app['name']:types.count(app['name']) for app in applications}
应用程序字典将为您提供类型中的应用程序计数。 这是您要找的东西吗?
您也可以使用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}
您可以使用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.')
输出:
app1 has 2 types.
app2 has 0 types.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.