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

โปรแกรม Python ทำเครื่องหมายสมาชิกซ้ำในลิสต์สตริง


ตัวอย่าง

โค้ดด้านล่างเพิ่มหมายเลขลำดับการปรากฏต่อท้ายสตริงที่ซ้ำกัน โดยใช้ list comprehension และ count()

my_list = ["python", "is", "fun", "python", "is", "fun", "python", "fun"]
print("The list is :")
print(my_list)
my_result = [value + str(my_list[:index].count(value) + 1) if my_list.count(value) > 1 else value for index, value in enumerate(my_list)]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : ['python', 'is', 'fun', 'python', 'is', 'fun', 'python', 'fun']
The result is : ['python1', 'is1', 'fun1', 'python2', 'is2', 'fun2', 'python3', 'fun3']

คำอธิบาย

  • กำหนดลิสต์สตริงและแสดงผล

  • ใช้ list comprehension วน enumerate: ถ้าค่านั้นซ้ำ (count > 1) ให้ต่อท้ายด้วยลำดับที่ปรากฏ (นับจาก slice my_list[:index] + 1)

  • ถ้าไม่ซ้ำ ให้คงค่าเดิม

  • แสดงผลลัพธ์