ที่นี่เราพยายามพิมพ์ตัวเลขซ้ำทั้งหมดจากลิสต์ของตัวเลข ดังนั้นเราพยายามพิมพ์ตัวเลขทั้งหมดที่เกิดขึ้นมากกว่าหนึ่งครั้งในลิสต์ (ไม่ unique ในลิสต์)
ตัวอย่าง
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]
ด้านล่างคือโค้ดสำหรับหา duplicate elements จากลิสต์ที่กำหนด −
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']