Python 代碼閱讀合集介紹:為什么不推薦Python初學者直接看專案原始碼
本篇閱讀的代碼實作了從輸入串列中尋找奇偶例外項,
本篇閱讀的代碼片段來自于30-seconds-of-python,
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函式接收一個串列,并回傳串列中的奇偶例外項,奇偶例外項指的是和串列中大多數項奇偶性質不同的項,函式使用串列推導式來逐個檢查輸入串列中的每一項是否為奇偶例外項,Counter中使用串列推導式和取余操作(% 2)逐個提取其輸入串列每項的奇偶性質,使用collections.Counter.most_common()來獲取串列中最常見的奇偶性,
class collections.Counter([iterable-or-mapping])
Counter是一個dict的子類,用于計數可哈希物件,它是一個集合,元素像字典鍵(key)一樣存盤,它們的計數存盤為值,計數可以是任何整數值,包括0和負數,most_common([n])是Counter提供的一個方法,該方法
回傳一個串列,其中包含n個最常見的元素及出現次數,按常見程度由高到低排序, 如果n被省略或為None,most_common()將回傳計數器中的所有元素, 計數值相等的元素按首次出現的順序排序,
>>> from collections import Counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
[0][0]是在結果串列里面定位元素,會把最常出現的元素提取出來,
>>> Counter('abracadabra').most_common(3)[0][0]
'a'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/347273.html
標籤:其他
