Python程序从整数列表中打印重复项

2021年3月16日12:31:30 发表评论 990 次浏览

给定其中包含重复元素的整数列表。生成另一个列表的任务, 该列表仅包含重复的元素。简而言之, 新列表应包含出现多个元素。

例子 :

Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output : output_list = [20, 30, -20, 60]


Input :  list = [-1, 1, -1, 8]
Output : output_list = [-1]

下面是实现:

# Python program to print 
# duplicates from a list 
# of integers
def Repeat(x):
     _size = len (x)
     repeated = []
     for i in range (_size):
         k = i + 1
         for j in range (k, _size):
             if x[i] = = x[j] and x[i] not in repeated:
                 repeated.append(x[i])
     return repeated
  
# Driver Code
list1 = [ 10 , 20 , 30 , 20 , 20 , 30 , 40 , 50 , - 20 , 60 , 60 , - 20 , - 20 ]
print (Repeat(list1))
      
# This code is contributed 
# by Sandeep_anand

输出:

[20, 30, -20, 60]

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: