简体   繁体   中英

PYTHON: How do I add items of the same name together, and add them to a list in order to find the length of the list?

I have a list in a file of different animals which is opened and read in a function.

For example my list is:

Cats, Dogs, Cows, Cows, Cows, Sheep, Dogs, Sheep, etc.

How do I put these in a list which will group the same animals together and return the number of each animal in the list, for example for this list I want:

List = (1, 2, 3, 2)

This will then enable me to work out the length of this new list and give how many different animals there are.

Without using sets if possible.

Also, because it is in a function I cant be specific about each animal.

You can use the values of a collections.Counter object instantiated from the list:

from collections import Counter
l = ['Cats', 'Dogs', 'Cows', 'Cows', 'Cows', 'Sheep', 'Dogs', 'Sheep']
print(list(Counter(l).values()))

This outputs:

[1, 2, 3, 2]

The below uses pandas to create a DataFrame with your list.

You can then use the pandas value_counts function, which returns a Series containing counts of unique Animals.

import pandas as pd

myAnimals = {'Animals': ['Cats', 'Dogs', 'Cows', 'Cows', 'Cows', 'Sheep', 'Dogs', 'Sheep']}
myList = pd.DataFrame(myAnimals)

pd.value_counts(myList['Animals'].values)

I find the output of this method more straight-forward:

Cows     3
Sheep    2
Dogs     2
Cats     1

See value_counts for more information.

You could use groupby from pandas

    import pandas as pd

    listOfAnimalsDF = pd.DataFrame({"Animal": ["Cats", "Dogs", "Cows", "Cows", "Cows", "Sheep", "Dogs", "Sheep"]})
    grouped = listOfAnimalsDF.groupby(by="Animal")

    print(grouped.groups)

For more Information about the pandas.DataFrame.groupby

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM