使用 Python 中的 Lambda 表示式和 reduce 函式查詢在列表中出現奇數次數的數字
在本文中,我們要找出列表中出現奇數次的數字。我們還需要使用 lambda 函式和 reduce 函式。
我們設計了一個函式,其中透過應用 lambda 函式來檢查元素是否出現奇數次,從而使用 reduce 函式。
示例
from functools import reduce def oddcount(i): print(reduce(lambda x, y: x ^ y, i)) listA = [12,34,12,12,34] print("Given list:\n",listA) print("The element present odd number of times:") oddcount(listA)
輸出
執行以上程式碼,結果如下 -
Given list: [12, 34, 12, 12, 34] The element present odd number of times: 12
廣告