The Python code implements finding odd even exceptions in the list
- 2021-12-12 09:16:17
- OfStack
The code snippet read in this article comes from 30-seconds-of-python.
1.find_parity_outliers
from collections import Counter
def find_parity_outliers(nums):
return [
x for x in nums
if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]
]
# EXAMPLES
find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3]
find_parity_outliers
The function receives a list and returns parity exceptions in the list. Parity exception items refer to items with different parity properties from most items in the list. The function uses a list derivation to check whether every 1 item in the input list is an odd-even exception.
Counter
Use list derivation and remainder operation (% 2) to extract the parity properties of each item in its input list one by one. Use
collections.Counter.most_common()
To get the most common parity in the list.
2.class collections.Counter([iterable-or-mapping])
Counter is a subclass of dict that counts hashable objects. It is a collection, the elements are stored like dictionary keys (key) 1, and their counts are stored as values. The count can be any integer value, including 0 and negative numbers.
most_common([n])
Yes
Counter
Provides 1 method that
Returns a list of the most common elements of n and the number of occurrences, sorted from most common to least common. If n is omitted or None, most_common () returns all elements in the counter. Elements with equal count values are sorted in the order in which they first appear.
>>> from collections import Counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
[0] [0] is to locate elements in the result list, which will extract the most common elements.
>>> Counter('abracadabra').most_common(3)[0][0]
'a'