在这里,我们尝试从数字列表中打印所有重复的数字。因此,我们正在尝试打印列表中出现多次(而不是唯一)的所有数字。
Input: given_list = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12] Output: desired_output = [3, 9, 12] Input: given_list = [-27, 4, 29, -27, -2 , -99, 123, 499, -99] Output: desired_output = [-27, -99]
以下是从给定列表中查找重复元素的代码-
lst = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12, 12] dupItems = [] uniqItems = {} for x in lst: if x not in uniqItems: uniqItems[x] = 1 else: if uniqItems[x] == 1: dupItems.append(x) uniqItems[x] += 1 print(dupItems)
输出结果
[3, 9, 12]
上面的程序不仅适用于整数列表,还适用于其他整数-
Input: given_list = ['abc','def','raj','zack','abc','raj'] Output: output_returned= ['abc', 'raj']