计数python中具有特定术语的子列表
我是个新手,我想写一个函数,输出包含特定元素的子列表的计数。但我的函数只是输出所有子列表中该特定项的总数 我的职能:计数python中具有特定术语的子列表,python,list,sublist,Python,List,Sublist,我是个新手,我想写一个函数,输出包含特定元素的子列表的计数。但我的函数只是输出所有子列表中该特定项的总数 我的职能: 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
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
tmp+=项目
到
tmp+=set(项目)
这将消除子列表中元素的重复计数。另一种写入方法是
def count(myList,ele):
tmp = []
key = 0
for item in myList:
if ele in item:
key += 1
return key
哦,现在我明白了。设置函数删除重复项是的,我得到了,谢谢你,如果我有帮助,请考虑选择答案!您不需要编写复杂的函数。中的
操作符告诉您列表中是否存在元素。例如:'a'在['a','b','c']==True
中。因此,检查子列表是否包含元素的函数是:def(toFind,list):return[toFind in l for l in list]
。要计算它们,只需执行以下操作:def(toFind,list):返回sum([toFind in l for l in list])