gpt4 book ai didi

python - 计算在 python 中具有特定术语的子列表

转载 作者:行者123 更新时间:2023-11-28 16:34:19 24 4
gpt4 key购买 nike

我是新手,我想编写一个函数来输出包含特定元素的子列表的计数。但是我的函数只输出所有子列表中该特定术语的总数。

我的功能:

def count(myList):
tmp = []
d = {}
for item in myList: tmp += item
for key in tmp: d[key] = d.get(key, 0) + 1
return d

我的输出:

>>res = count_doc_frequencies([['a', 'b', 'a'], ['a', 'b', 'c'], ['a']])
>>res['a']
4
>>res['b']
2

期望的输出:

>>res = count_doc_frequencies([['a', 'b', 'a'], ['a', 'b', 'c'], ['a']])
>>res['a']
3

因为 'a' 存在于 3 个子列表中..

谁能帮我修改我的函数以获得所需的输出??

最佳答案

lst = [['a', 'b', 'a'], ['a', 'b', 'c'], ['a']]

def count(lst):
# declare dictionary that we are going to return
foo = {}
# iterate sublist
for sublist in lst:
# make sublist into unique element list
sublist = list(set(sublist))
for element in sublist:
# if element found in foo dic, increment
if element in foo:
foo[element] += 1
# else, init with 1
else:
foo[element] = 1
return foo

res = count(lst)
print res

关于python - 计算在 python 中具有特定术语的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com