一行搞定-统计一句话中每个单词出现的个数
>>> s
'i am a boy a bood boy a bad boy'
方式一:
>>> dict([(i,s.split().count(i)) for i in s.split()])
{'a': 3, 'boy': 3, 'i': 1, 'am': 1, 'bad': 1, 'bood': 1}
>>> set([(i,s.split().count(i)) for i in s.split()])
set([('boy', 3), ('am', 1), ('i', 1), ('bood', 1), ('a', 3), ('bad', 1)])
方式二:
>>> set(map(lambda x:(x,s.split().count(x)),s.split()))
set([('boy', 3), ('am', 1), ('i', 1), ('bood', 1), ('a', 3), ('bad', 1)])
>>> dict(map(lambda x:(x,s.split().count(x)),s.split()))
{'a': 3, 'boy': 3, 'i': 1, 'am': 1, 'bad': 1, 'bood': 1}