เมื่อต้องการเรียงลำดับสตริงตามจำนวนเครื่องหมายวรรคตอน (punctuation) สามารถใช้ฟังก์ชันช่วยที่มี list comprehension และ string.punctuation ได้
ตัวอย่าง
from string import punctuation
def get_punctuation_count(my_str):
return len([element for element in my_str if element in punctuation])
my_list = ["python@%^", "is", "fun!", "to@#r", "@#$learn!"]
print("The list is :")
print(my_list)
my_list.sort(key=get_punctuation_count)
print("The result is :")
print(my_list)
ผลลัพธ์
The list is : ['python@%^', 'is', 'fun!', 'to@#r', '@#$learn!'] The result is : ['is', 'fun!', 'to@#r', 'python@%^', '@#$learn!']
คำอธิบาย
นำเข้า
punctuationจากstring(สตริงของเครื่องหมายวรรคตอนทั้งหมด)กำหนดฟังก์ชันนับจำนวน punctuation ในสตริงด้วย list comprehension
กำหนดลิสต์สตริงที่มี punctuation แตกต่างกัน แสดงผล
ใช้
sort(key=get_punctuation_count)เรียงจากน้อยไปมากแสดงผลลัพธ์ (is=0, fun!=1, to@#r=3, python@%^=3, @#$learn!=4)