based on the following data:
restaurantes = [('Burger King', 'MA', 'Chicopee', '1284 Memorial Dr', '1020', '42.1927', '-72.5763'), ("Taco Bell", 'MA', 'Chicopee', '1606 Memorial Dr', '1020', '42.201117596', '-72.574102772'), ('Pizza Hut', 'MA', 'Easthampton', '113 Northampton St', '1027', '42.278666', '-72.671148'), ("Jack in the Box", 'MA', 'Holyoke', '285 Maple St', '1040', '42.20578', '-72.61053')]
I have managed to make the following function that returns the percentage of "x" restaurant brand in the restaurants variable:
def porcentaje_burger_king(restaurante, name):
nombres = [nombre for nombre, _, _, _, _, _, _ in restaurantes if nombre == name]
result = (len(nombres)/len(restaurantes))*100
return result
Which is executed with:
print(porcentaje(restaurantes, "Burger King")) #(0.25)
The problem is that I can't create a function that returns the percentage of each brand that is in the restaurant variable. I have tried with the following function, which gives wrong data:
def porcentajes_por_nombres(restaurantes):
nombres = [nombre for nombre, _, _, _, _, _, _ in restaurantes]
porcentajes = []
indice = 0
while indice < len(nombres):
porcentaje_x = (len(nombres[indice])/len(restaurantes))*100
porcentajes.append(porcentaje_x)
indice +=1
return porcentajes
print(porcentajes_por_nombres(restaurantes)) #Devuelve [275.0, 225.0, 225.0, 375.0] en vez de [0.25, 0.25, 0.25, 0.25]
I need the result in the form of a list, so that I can later use the zip function with the variables names and percentages, thanks in advance.
You unpack the tuple to extract the name, but you don't care about the rest of the elements, so you use
_
. Consider not unpacking it and instead use an index to fetch the first element, like this:Naturally that will give you repeated names, which is fine for the function that wants to count how many times each name appears, since
len(nombres)
it gives you that data. But for the other function where you just need to collect all the names, you don't want them to be repeated. For this you could use a set:You could then iterate through that set and make use of the other function, to calculate the percentage. You can save the tuples (name, percentage) in a list, to return that list directly and not have to do
zip()
. For example like this:Alternative
An even simpler and shorter way is to make use of the standard module
collections
, which has a classCounter()
that is precisely used to count the number of times an element is repeated within an iterable.We can use it to count the names of restaurants:
The result of the count is a dictionary in which each key is a different element (restaurant name) and the value is an integer with the number of times it has been repeated. From that it is trivial to create your list of (name, percentage):
Result: