Python程式查詢列表中出現奇數次的元素


當需要查詢列表中出現奇數次的元素時,可以定義一個方法。此方法遍歷列表並檢查巢狀迴圈中的元素是否匹配。如果匹配,則計數器遞增。如果該計數不能被 2 整除,則將列表的特定元素作為結果返回。否則,返回 -1 作為結果。

下面是相同內容的演示 -

示例

 線上演示

def odd_occurence(my_list, list_size):

   for i in range(0, list_size):
      count = 0
      for j in range(0, list_size):
         if my_list[i] == my_list[j]:
            count+= 1

      if (count % 2 != 0):
         return my_list[i]

   return -1
my_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56 ]
print("The list is :")
print(my_list)
n = len(my_list)
print("The length is :")
print(n)
print("The method to find the element that occurs odd number of times is called ")
print("The element that occurs odd number of times is :")
print(odd_occurence(my_list, n))

輸出

The list is :
[34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
The length is :
17
The method to find the element that occurs odd number of times is called
The element that occurs odd number of times is :
34

解釋

  • 定義了一個名為“odd_occurence”的方法,它將列表及其大小作為引數。

  • 將列表大小作為範圍,並遍歷列表。

  • 迭代兩個巢狀迴圈,如果列表中的元素與第一個和第二個迴圈迭代匹配,“count”變數遞增。

  • 如果“count”變數是奇數,則返回列表中的特定元素。

  • 定義一個整數列表並在控制檯上顯示。

  • 將列表的長度儲存在一個變數中。

  • 透過傳遞相關引數來呼叫該方法。

  • 在控制檯上顯示輸出。

更新於: 2021年4月14日

1K+ 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.