I have a list of lists, which looks like
listOfLists = [
['a','b','c','d'],
['a','b'],
['a','c'],
['c','c','c','c']
]
I want to count the number of lists which have a particular element. For Example, my output should be
{'a':3,'b':2,'c':3,'d':1}
As you can see, I don't need the total count of an element. In the case of "c"
, though its total count is 5, the output is 3 as it occurs only in 3 lists.
I am using a counter to get the counts. The same can be seen below.
line_count_tags = []
for lists in lists_of_lists:
s = set()
for element in lists:
s.add(t)
lines_count_tags.append(list(s))
count = Counter([count for counts in lines_count_tags for count in counts])
So, when I print count, I get
{'a':3,'c':3,'b':2,'d':1}
I want to know if there's a much better way to accomplish my goal.
The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
Len() Method There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.
Count how often a single value occurs by using the COUNTIF function. Use the COUNTIF function to count how many times a particular value appears in a range of cells.
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
Use a Counter
and convert each list to a set. The set
will remove any duplicates from each list so that you don't count duplicate values in the same list:
>>> from collections import Counter
>>> Counter(item for lst in listOfLists for item in set(lst))
Counter({'a': 3, 'b': 2, 'c': 3, 'd': 1})
If you like functional programming you can also feed a chain
of set
-map
ped listOfLists
to the Counter
:
>>> from collections import Counter
>>> from itertools import chain
>>> Counter(chain.from_iterable(map(set, listOfLists)))
Counter({'a': 3, 'b': 2, 'c': 3, 'd': 1})
Which is totally equivalent (except maybe being a bit faster) to the first approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With