我有一個代碼如下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