使用 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

更新於:2020-06-04

255 次瀏覽

開啟你的 職業生涯

透過完成這門課程獲得認證

瞭解更多
廣告