[英]how to group element's of a list with respect of some information in each elements?
我有一个清单。 我列表中的每个元素都是这样的:
list[0]={'Keywords': ' foster care case aide ',
'categoryId': '1650',
'result': {'categoryId': '1650',
'categoryName': 'case aide',
'score': '1.04134220123291'}}
我可以收集同一组中具有相同categoryId
的所有关键字吗? 并为每个categoryId
计算我有多少个keywords
?
如果不可能,请告诉我
您可以使用collections.defaultdict
为每个categoryId
设置一set
并添加相关单词:
from collections import defaultdict
output = defaultdict(set)
for entry in list:
kwds = entry['Keywords'].strip().split(' ')
for word in kwds:
output[entry['categoryId']].add(word)
我正在使用一个set
,因为我假设您不希望每个categoryId
中的单词重复。 您可以改为使用list
或其他集合。
然后你可以得到每个 ID 的大小:
for k, v in output.items():
print(f'ID: {k}, words: {len(v)}')
# ID: 1650, words: 4
回应OP的评论:
如果您收到KeyError: 'categoryId'
,这意味着某些条目没有键'categoryId'
。 如果您只想跳过这些条目,可以在上述解决方案中添加一个小问题:
for entry in list:
# catch if there is a missing ID field
if entry.get('categoryId', None) is None:
break
# otherwise the same
kwds = entry['Keywords'].strip().split(' ')
for word in kwds:
output[entry['categoryId']].add(word)
如果没有categoryID
,循环将break
,条目将被跳过。
请注意,我们也依赖于那里的"Keywords"
字段,因此您可能还需要为此添加一个catch。
或者,如果您想从没有 ID 的条目中收集所有关键字,您可以在原始解决方案中使用dict.get()
:
for entry in data:
kwds = entry['Keywords'].strip().split(' ')
for word in kwds:
output[entry.get('categoryId', None)].add(word)
现在如果没有categoryId
,则关键字将添加到output
中的键None
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.