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

เรียงลำดับคำศัพท์ใน Python


การจัดเรียงคำตามลำดับศัพท์หมายความว่าเราต้องการจัดเรียงคำเหล่านั้นก่อนด้วยตัวอักษรตัวแรกของคำ จากนั้นสำหรับคำที่มีตัวอักษรตัวแรกเหมือนกัน เราจะจัดเรียงภายในกลุ่มนั้นด้วยตัวอักษรตัวที่สองและต่อไปเรื่อยๆ เช่นเดียวกับในพจนานุกรมของภาษา (ไม่ใช่โครงสร้างข้อมูล)

Python มี 2 ฟังก์ชัน sort และ sorting สำหรับคำสั่งประเภทนี้ ให้เรามาดูว่าจะใช้แต่ละ method อย่างไรและเมื่อไหร่

In place sorting:เมื่อเราต้องการเรียงลำดับ array/list ให้เข้าที่ เช่น การเปลี่ยนลำดับในโครงสร้างปัจจุบัน เราสามารถใช้วิธี 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']

ดังที่คุณเห็นที่นี่ อาร์เรย์ดั้งเดิม my_arr ได้รับการแก้ไขแล้ว หากคุณต้องการคงอาร์เรย์นี้ไว้ตามเดิม และสร้างอาร์เรย์ใหม่เมื่อทำการเรียงลำดับ คุณสามารถใช้วิธีการเรียงลำดับได้ ตัวอย่างเช่น

ตัวอย่าง

my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)
# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)

ผลลัพธ์

สิ่งนี้จะให้ผลลัพธ์ -

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

ดังที่คุณเห็นที่นี่ อาร์เรย์เดิมไม่มีการเปลี่ยนแปลง