2014-03-03 89 views
0

我想要計算一個單詞在列表中的頻率,使用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 
+1

的Python 2:'圖(拉姆達X:Y,Z)'→ '[y for z in z]' – Ryan

+0

我正在試圖用len或者減少 – user3376297

+2

那麼,不要。使用['collections.Counter'](http://docs.python.org/3.4/library/collections.html#collections.Counter)。 – Ryan

回答

0

我們將有一個列表:要解決這個問題cars = ['nissan','nobel','nobel', 'porsche', 'merc', 'merc', 'porsche', 'aston martin']

一種方法是遍歷列表。我們將初始化一個字典,carCounts,即保持的每一輛汽車出現了多少次

carCounts = defaultdict(int) 
for car in cars: 
    carCounts[car] += 1 
print carCounts 
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}) 
相關問題