[Tutor] Counting Items on a List associated w/ Index #

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 3 14:41:39 EDT 2018


On 03/08/18 12:14, Rafael Knuth wrote:

> I wrote a function which is supposed to count the number of items on
> each index #.
> For starters, here's a list I created to test the function:
> 
> properties = ["mansion, modern, swimming_pool" , "mansion, historic,
> air_conditioning", "penthouse, modern, whirlpool"]

Storing multiple fields in a single string is nearly always
the wrong thing to do. It would be much easier to work with
tuples of three strings. Always try to make your data look
as much like what you are trying to model as possible.

However...

> def feature_counter(input_lst, index, input_str):
>     num_elt = 0
>     output_lst = []
>     for row in input_lst:
>         split_row = row.split(",")

By splitting on the comma you leave the prefix
space in place for the 2nd and 3rd items.
You need to strip() that off before using it.

>         output_lst.append(split_row)

T^his is exactly the pattern that matches a list
comprehension so you could write all of the above as:

def feature_counter(input_lst, index, input_str):
    num_elt = 0
    output_lst = [row.split(',').strip() for row in input_lst]


And you wouldn't need to do it at all if you stored
the base data as tuples of strings...

>     for each in output_lst:
>         if each[index] == input_str:
>             num_elt = num_elt + 1
>     return num_elt
> 
> This function returns the correct result when checking index 0:
> 
> print(feature_counter(properties, 0, "mansion"))
>>>> 2
> 
> Weirdly, it returns the wrong result when checking index 1:
> and index 2:
> 
> print(feature_counter(properties, 2, "swimming_pool"))
>>>> 0

That's because of the leading spaces.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list