[Tutor] How many times X is in a list?

Kent Johnson kent37 at tds.net
Wed Dec 20 19:12:58 CET 2006


Carlos wrote:
> Hello,
> 
> Can you help me with this please?
> 
> I have a list that contains elements to be created (in a 3D app), in the 
> list each element is a dictionary that contains data, like:
> 
> Elements = [
>             {'Width': 3.0, 'Depth': 3.0, 'Name': 'Access', 'Parent': 
> 'Plot', 'Height': 3.0},
>             {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_01', 
> 'Parent': 'Access', 'Height': 3.0},
>             {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_02', 
> 'Parent': 'Access', 'Height': 3.0},
>             {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_03', 
> 'Parent': 'Access', 'Height': 3.0},
>             {'Width': 2.0, 'Depth': 6.0, 'Name': 'Int_Circ_01', 
> 'Parent': 'Circulation_01', 'Height': 3.0},
>             {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_02', 
> 'Parent': 'Circulation_01', 'Height': 3.0},
>             {'Width': 2.0, 'Depth': 6.5, 'Name': 'Int_Circ_03', 
> 'Parent': 'Circulation_02', 'Height': 3.0},
>             {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_04', 
> 'Parent': 'Circulation_02', 'Height': 3.0},
>             {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_05', 
> 'Parent': 'Circulation_03', 'Height': 3.0},
>             {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_06', 
> 'Parent': 'Circulation_03', 'Height': 3.0},
>                   ]
> 
> so a for loop is used to iterate the list, like:
> 
> for element in elements:
>     create object with the desired width, depth, name, etc
> 
> The thing is that there can only be a "Circulation" by story, so I am 
> thinking in adding each created object to a built_Objects list and 
> appending the created object to the list, like:
> 
> for element in elements:
>     create element
>     append element['Name'] to built_Objects
> 
> My question is, how can I check how many times "Circulation" appears in 
> the built_Objects list? I think that if I get the number of times /N/ 
> that "Circulation" appears I can multiply the next circulation elevation 
> /N/ times and avoid having two circulations in the same level. Is this a 
> correct reasoning?
> 
> I did a little research and found that count could help me, so I tried:
> 
> print Built_Elements.count('Circulation')
> 
> but well is not working. The result is 0, I guess that count is looking 
> for the exact term and not something similar
> 
> If you know the solution or a better way to do this please let me know.

Yes, count() is looking for exact matches. You can make a new list with 
just the circulation names and take the length of that; something like this:
len([name for name in built_Objects if name.startswith('Circulation')])

or perhaps slightly more efficient (Python 2.5):
sum(1 for name in built_Objects if name.startswith('Circulation'))

Kent



More information about the Tutor mailing list