Python count elements in list with condition
Ngày đăng:
07/12/2021
Trả lời:
0
Lượt xem:
141
How do I count items in a list based on a condition in Python.2019-02-13There are many ways to count the occurrences of items in a list based on a condition. Here you will see two of them: one example with map and one example by using list comprehension. Start by creating a list of names. Note that chuck appears twice in the list. Show >>> names = ["vera", "chuck", "dave", "chuck"]
>>> names
['vera', 'chuck', 'dave', 'chuck']
Count occurrences by using MapBy using map you can provide a lambda with the condition like this: >>> map(lambda x: x == "chuck", names)
This results in a map object that we can inspect by converting it to a list: >>> list(map(lambda x: x == "chuck", names))
[False, True, False, True]
You see that the map has converted the values in the list names to boolean values. If you replace list with sum, Python will calculate the total of True values: >>> sum(map(lambda x: x == "chuck", names))
2
Count occurrences by using List comprehensionList comprehension is another way to map lists to create new lists. You can start by using a list comprehension that does not filter the list at all and thus returns a copy of the original list: >>> [n for n in names]
['vera', 'chuck', 'dave', 'chuck']
To filter that list, you can use if: >>> [n for n in names if n == "chuck"]
['chuck', 'chuck']
Now use the len function to count the occurrences: >>> len([n for n in names if n == "chuck"])
2
Written by Loek van den Ouweland on 2019-02-13. Questions regarding this artice? You can send them to the address below.
|