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”變數是奇數,則返回列表中的特定元素。
定義一個整數列表並在控制檯上顯示。
將列表的長度儲存在一個變數中。
透過傳遞相關引數來呼叫該方法。
在控制檯上顯示輸出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP