Count each unique element in list of lists

  • Thread starter Yaþar Arabacý
  • Start date
Y

Yaþar Arabacý

Hi,

I have a function that returns something like this;

[[[1, 5, 9], [2, 6, 7], [3, 4, 8]], [[1, 6, 8], [2, 4, 9], [3, 5, 7]]]

It is a list of list of lists. Each uppermost list is called a result.
I want to write a code that
shows that each elem in sublists of result on appears once in whole
sublist in order to add it to
my doctest. I am looking for something like this;

for result in results:
print sum(1 for group in result for item in group)

[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1]

Above code gives me 9,9. but I want the example output above.

I prefer a one liner because this is supposed to go into a doctest.
 
Y

yasar11732

This works;
flat = list(item for group in result for item in group)
print [sum([1 for el in flat if el==current]) for current in flat]


[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1]

But I am still open to suggestions if anyone thinks this can be improved.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top