counting elements in a list of lists

This is the place for queries that don't fit in any of the other categories.

counting elements in a list of lists

Hi guys! I want to code a for loop from which:
Code: Select all
[['welcome', 'a1'],['welcome', 'a1'],['welcome', 'b1'],['hello', 'c1'],...]

It has to return:
Code: Select all
[['welcome', 'a1', 2],['welcome', 'b1', 1],['hello', 'c1', 1],...]

I have a for loop that counts elements in a list of lists:
Code: Select all
res =[list(x) + [1] for x in set(map(tuple, listWords))]

that returns:
Code: Select all
[['welcome', 'a1', 1],['welcome', 'a1', 1],['welcome', 'b1',1],['hello', 'c1', 1],...]

I don't want this

Thank you for your help!
JuanPabloPerez

Posts: 2
Joined: Sun Aug 18, 2013 7:34 am
Location: Mexico

Re: counting elements in a list of lists

I see that your loop comprehension uses a set, so I'm assuming order doesn't matter.

If you don't specifically need the result to be a list of lists, you can use collections.Counter to do this the easy way:
Code: Select all
>>> from collections import Counter
>>> L = [['welcome', 'a1'],['welcome', 'a1'],['welcome', 'b1'],['hello', 'c1']]
>>> Counter(map(tuple, L))
Counter({('welcome', 'a1'): 2, ('hello', 'c1'): 1, ('welcome', 'b1'): 1})

If you do need a list of lists as a result, this should be pretty easy to convert.

If you want to do this manually(or order matters), here's one possible approach(simple rather than efficient):
• Loop through each sublist, keeping note of already seen elements
• If element wasn't seen yet:
• Use list.count() to count how many times it's there.
• Create a list from this information and append it to the results
• If element was seen, skip it
Friendship is magic!

R.I.P. Tracy M. You will be missed.

stranac

Posts: 1478
Joined: Thu Feb 07, 2013 3:42 pm

Re: counting elements in a list of lists

Thank you for your reply but how can I get the vector with the counts? like e.g. [1,1,2,1] from the code above. Should It be a key thing?
Code: Select all
def vectors(lista):
r=[]
for e in lista:
r.append(lista.keys)
return r

JuanPabloPerez

Posts: 2
Joined: Sun Aug 18, 2013 7:34 am
Location: Mexico

Re: counting elements in a list of lists

Why would you get [1,1,2,1] from the code above?

For my first suggestion, simply using .values() on the Counter object should be enough. But this won't work if the order matters.
For the second one, something like [sub[-1] for sub in result] should work.

But it's really hard to give you good help, since it's not clear what you really want.
Friendship is magic!

R.I.P. Tracy M. You will be missed.

stranac

Posts: 1478
Joined: Thu Feb 07, 2013 3:42 pm