เมื่อต้องการดึงสมาชิกจากลิสต์ที่หลักตัวเลขเรียงลำดับเพิ่มขึ้น (strictly increasing) สามารถใช้ลูป iteration, ค่า flag และ str() ได้
ตัวอย่าง
my_list = [4578, 7327, 113, 3467, 1858]
print("The list is :")
print(my_list)
my_result = []
for element in my_list:
my_flag = True
for index in range(len(str(element)) - 1):
if str(element)[index + 1] <= str(element)[index]:
my_flag = False
if my_flag:
my_result.append(element)
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [4578, 7327, 113, 3467, 1858] The result is : [4578, 3467]
คำอธิบาย
กำหนดลิสต์ตัวเลขและแสดงผล
สร้างลิสต์ว่างผลลัพธ์
วนลูปแต่ละตัวเลข ตั้ง flag=True แปลงเป็นสตริง เปรียบเทียบหลักติดกัน
ถ้าหลักถัดไป <= หลักปัจจุบัน flag=False (ไม่ได้เรียงเพิ่มขึ้นอย่างเคร่งครัด)
ถ้า flag ยังคง True เพิ่มตัวเลขนั้นในผลลัพธ์
แสดงผลลัพธ์ (4578: 4<5<7<8, 3467: 3<4<6<7)