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

Python – ทดสอบว่าความยาวแถวเพิ่มขึ้นตามลำดับ

เมื่อต้องการทดสอบว่าความยาวของแถว (สับลิสต์) ในเมทริกซ์เพิ่มขึ้นตามลำดับหรือไม่ สามารถใช้ลูป iteration และค่า Boolean ได้

ตัวอย่าง

my_list = [[55], [12, 17], [25, 32, 24], [58, 36, 57, 19, 14]]
print("The list is :")
print(my_list)
my_result = True
for index in range(len(my_list) - 1):
    if len(my_list[index + 1]) <= len(my_list[index]):
        my_result = False
        break
print("The result is :")
if my_result == True:
    print("The rows are increasing in length")
else:
    print("The rows aren't increasing in length")

ผลลัพธ์

The list is : [[55], [12, 17], [25, 32, 24], [58, 36, 57, 19, 14]]
The result is : The rows are increasing in length

คำอธิบาย

  • กำหนดเมทริกซ์ที่ความยาวแถวเพิ่มขึ้นทีละ 1 และแสดงผล

  • ตั้งค่า flag my_result = True

  • วนลูปดัชนี 0 ถึง len-2 เปรียบเทียบความยาวแถวปัจจุบันกับแถวถัดไป

  • ถ้าแถวถัดไปสั้นกว่าหรือเท่ากัน flag=False break

  • แสดงข้อความตาม flag (ตัวอย่างผ่านเงื่อนไข)