计算列表中的单词

时间:2014-03-03 19:39:33

标签: python map lambda

我正在尝试计算列表中单词的频率,使用len()但是它不起作用,我创建了一个汽车列表然后随机使用我基本上打印汽车20次,所以随机正在创造20辆随机汽车,但现在我正在尝试计算每辆汽车的创建次数,但它不起作用它只显示5次,20次?

carslist =["aston martin", "nissan", "nobel", "Porsche", "merc"] 
randomGen = map(lambda x : random.randint(0,5), range(20))
cars= map(lambda i: carslist[i], randomGen)
print cars

#not working, trying to count how many times each car is being printed
lengths = map (lambda x: len(carsList), cars)
print lengths

2 个答案:

答案 0 :(得分:0)

我们会有一个列表:cars = ['nissan','nobel','nobel', 'porsche', 'merc', 'merc', 'porsche', 'aston martin']

解决此问题的一种方法是迭代列表。我们将初始化一个字典carCounts,用于跟踪每辆车出现的次数

carCounts = defaultdict(int)
for car in cars:
  carCounts[car] += 1
print carCounts

答案 1 :(得分:0)

使用Counter

carslist = ["aston martin", "nissan", "nobel", "Porsche", "merc"] 
randomGen = map(lambda x: random.randint(0, 4), range(20))
cars = map(lambda i: carslist[i], randomGen)

from collections import Counter
lengths = Counter(cars)
print lengths
# Counter({'merc': 6, 'nissan': 4, 'nobel': 4, 'Porsche': 3, 'aston martin': 3})