Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python พิมพ์ค่าที่ไม่ซ้ำจากลิสต์


พิมพ์ค่าที่ไม่ซ้ำกัน (unique) จากลิสต์โดยเก็บในลิสต์ใหม่และเช็คก่อนเพิ่ม

ตัวอย่าง

Input: [1,2,3,4,2,1,9]
Output: [1,2,3,4,9]

อัลกอริทึม

  1. สร้างลิสต์ว่าง uniquevalues
  2. วนลูปทุกอิลิเมนต์
  3. ถ้ายังไม่มีใน uniquevalues ให้ append
  4. พิมพ์ผลลัพธ์

โค้ดตัวอย่าง

def unique(A):
    uniquevalues = []
    for i in A:
        if i not in uniquevalues:
            uniquevalues.append(i)
    for i in uniquevalues:
        print(i, end=' ')

A = []
n = int(input("Enter the size of the List: "))
print("Enter the Elements:")
for _ in range(n):
    A.append(int(input()))
print("The unique values from the List is:")
unique(A)

ผลลัพธ์

Enter the size of the List: 6
Enter the Elements: 1 2 5 2 1 7
The unique values from the List is: 1 2 5 7