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

ตรวจสอบว่าลิสต์เรียงลำดับหรือไม่ใน Python

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

ด้วย sort

เราก็อปปี้ลิสต์ที่กำหนด ใช้ฟังก์ชัน sort กับมันและเก็บก็อปปี้นั้นเป็นลิสต์ใหม่ จากนั้นเปรียบเทียบกับลิสต์ต้นฉบับและตรวจสอบว่าทั้งสองเท่ากันหรือไม่

ตัวอย่าง

listA = [11, 23, 42, 51, 67] # Given list
print("Given list : ", listA)
listA_copy = listA[:] # Apply sort to copy
listA_copy.sort()
if (listA == listA_copy):
    print("Yes, List is sorted.")
else:
    print("No, List is not sorted.")
# Checking again
listB = [11, 23, 21, 51, 67] # Given list
print("Given list : ", listB)
listB_copy = listB[:] # Apply sort to copy
listB_copy.sort()
if (listB == listB_copy):
    print("Yes, List is sorted.")
else:
    print("No, List is not sorted.")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

Given list : [11, 23, 42, 51, 67]
Yes, List is sorted.
Given list : [11, 23, 21, 51, 67]
No, List is not sorted.

ด้วย all และ range

เราสามารถใช้ฟังก์ชัน all เพื่อตรวจสอบว่าทุกองค์ประกอบของลิสต์น้อยกว่าหรือเท่ากับองค์ประกอบถัดไป และใช้ฟังก์ชัน range เพื่อวนลูปผ่านทุกองค์ประกอบ

ตัวอย่าง

listA = [11, 23, 42, 51, 67] # Given list
print("Given list : ", listA)
# Apply all and range
if (all(listA[i] <= listA[i + 1] for i in range(len(listA)-1))):
    print("Yes, List is sorted.")
else:
    print("No, List is not sorted.")
# Checking again
listB = [11, 23, 21, 51, 67]
print("Given list : ", listB)
# Apply all and range
if (all(listB[i] <= listB[i + 1] for i in range(len(listB)-1))):
    print("Yes, List is sorted.")
else:
    print("No, List is not sorted.")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

Given list : [11, 23, 42, 51, 67]
Yes, List is sorted.
Given list : [11, 23, 21, 51, 67]
No, List is not sorted.