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

เรียงคำตามลำดับ Lexicographical ใน Python

การเรียงคำ lexicographical order หมายถึงจัดเรียงตามตัวอักษรตัวแรกของคำ แล้วคำที่ตัวแรกเหมือนกัน เรียงตามตัวที่สอง ต่อไป เช่นพจนานุกรม

Python มี sort และ sorted สำหรับการเรียงนี้

In-place sorting: ใช้ sort() โดยตรง

my_arr = ["hello", "apple", "actor", "people", "dog"]
print(my_arr)
my_arr.sort()
print(my_arr)

ผลลัพธ์

['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']

อาร์เรย์เดิมเปลี่ยน ถ้าต้องการเก็บเดิมใช้ sorted()

ตัวอย่าง

my_arr = ["hello", "apple", "actor", "people", "dog"]
print(my_arr)
new_arr = sorted(my_arr)
print(new_arr)
print(my_arr)

ผลลัพธ์

['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
['hello', 'apple', 'actor', 'people', 'dog']