Question

I am trying to count the frequency of a word in a list, using the len() but it's not working, I created a car list and then using random I am basically printing the cars 20 times, so the random is creating 20 random cars, but now I am trying to count how many times each car is being created, but its not working it just displays 5, 20 times?

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

No correct solution

OTHER TIPS

We'll have a list: cars = ['nissan','nobel','nobel', 'porsche', 'merc', 'merc', 'porsche', 'aston martin']

One way to solve this problem is to iterate over the list. We'll initialize a dictionary, carCounts, that keeps track of how many times each car appears

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

Use a 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})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top