[Python] - Extract group of items from a list?

Hi,

I would like to be able to get informations from a list.
I think that some python functions would be useful but I couldn’t find relevant informations.

Example


itemList=["apple", "banana", "apple", "apple", "peach", "peach","peach", "peach"]

<i>#The script would calculate (how?) and then display :</i>

number of groups : 3<i> ("apple", "banana","peach")</i>

name of group : "apple"
number of "apple" items : 3

name of group : "banana"
number of "banana" items : 1

name of group : "peach"
numner of "peach" items : 4

Maybe something similar to the sql ‘group by’ would help?

Would you show me a part of script, or point me to relevant functions/resources please?

Note
I get itemList from a scan of all the objets in the scene : items are appended automatically so I don’t know what is in the list.

There should be no need to “calculate” anything if you use a dictionary:


dict = {}

dict["apple"] = 1
dict["apple"] += 1

print dict["apple"] # 2

dict["whateverelseyouwant"] = 1000
dict["whateverelseyouwant"] *= dict["apple"]
print dict["whateverelseyouwant"] # 2000

Documentation to look at: http://diveintopython.org/getting_to_know_python/dictionaries.html

fast(?) count procedure


itemList=["apple", "banana", "apple", "apple", "peach", "peach","peach", "peach"]
itemCounts = {}
for item in itemList:
    try:
        itemCounts[item] += 1 # the key existed, and 1 to the count
    except:
        itemCounts[item] = 1 # the key didn't exist, create it
print itemCounts

this outputs a dictionary: {‘apple’: 3, ‘peach’: 4, ‘banana’: 1}… you can include that routine in your object scan code, saving everything in a dictionary at once.

You can avoid try/except too…

itemList=["apple", "banana", "apple", "apple", "peach", "peach","peach", "peach"]
itemCounts = {}
for item in itemList:
    itemCounts.setdefault(item, 1 + itemCounts.get(item, 0))

print itemCounts

Thank you all for your great help.
It worked perfectly.

Dictionaries are so powerful :eek: