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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 定义了一个名为“odd_occurence”的方法,它将列表及其大小作为参数。

  • 将列表大小作为范围,并遍历列表。

  • 迭代两个嵌套循环,如果列表中的元素与第一个和第二个循环迭代匹配,“count”变量递增。

  • 如果“count”变量是奇数,则返回列表中的特定元素。

  • 定义一个整数列表并在控制台上显示。

  • 将列表的长度存储在一个变量中。

  • 通过传递相关参数来调用该方法。

  • 在控制台上显示输出。

更新于: 2021年4月14日

1K+ 次查看

开启你的职业生涯

通过完成课程获得认证

开始学习
广告