我有一个代码如下python list counting elements
我怎样才能找到abc是一个由列表组成的列表?
我的地图功能有什么问题?
我想我的函数返回我的输入列表中每个元素的计数除以我的列表的长度。
喜欢的东西
{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666, 'dog': 0.16666666666666666, 'quick': 0.16666666666666666}
我的代码:
quickbrownfox1=['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']
print quickbrownfox1
def tf(tokens):
abc=([[x,(tokens.count(x))] for x in set(tokens)])
print type(abc)#how to know that abc is made up of lists
print type(abc[1])
answer=abc.map(lambda input:(input(0)),input(1)/len(tokens)))
return answer
#return <FILL IN>
print tf((quickbrownfox1)) # Should give { 'quick': 0.1666 ... }
#print tf(tokenize(quickbrownfox)) # Should give { 'quick': 0.1666 ... }
_______________________________________
更新1
我如下更新我的代码。我得到结果[('brown', 0), ('lazy', 0), ('jumps', 0), ('fox', 0), ('dog', 0), ('quick', 0)]
任何想法为什么?如果我做return return list(map(lambda input: (input[0], input[1]), abc))
,它给出正确的结果 - [('brown', 1), ('lazy', 1), ('jumps', 1), ('fox', 1), ('dog', 1), ('quick', 1)]
from __future__ import division
quickbrownfox1=['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']
def islistoflists(i):
if isinstance(i, list):
if len(i) > 0 and all(isinstance(t, list) for t in i):
return True
return False
def tf(tokens):
print(islistoflists(tokens))
abc = ([[x,tokens.count(x)] for x in set(tokens)])
return list(map(lambda input: (input[0], input[1]/len(tokens)), abc))
print tf(quickbrownfox1)
更新2
我使用pyspark /火花。这可能是我在update1中遇到的问题的原因吗?
'是列表组成的列表?在abc上做一个for循环,然后用'type()'检查每个元素。如果他们都列出,那么你得到你想要的。 – GLHF
['map'](https://docs.python.org/3/library/functions.html#map)是一个内建函数,不是方法,所以'abc.map'它不起作用,你必须使用'map(function,abc)' – Copperfield