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

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

เงื่อนไขสามเหลี่ยม: ผลรวมสองด้านต้องมากกว่าด้านที่สาม ตรวจสอบ sublist ไหนที่ตรงเงื่อนไข

ใช้ for และ >

เรียง sublist แล้วเช็ค e[0]+e[1] > e[2]

ตัวอย่าง

Alist = [[3, 8, 3], [9, 8, 6]]
for x in Alist:
    x.sort()
for e in Alist:
    if e[0] + e[1] > e[2]:
        print("The sublist showing triangular inequality:", e)

ผลลัพธ์

The sublist showing triangular inequality: [6, 8, 9]

ใช้ list comprehension

[(x,y,z) for x,y,z in Alist if (x+y) >= z]

ตัวอย่าง

Alist = [[3, 8, 3], [9, 8, 6]]
for x in Alist:
    x.sort()
if [(x, y, z) for x, y, z in Alist if (x + y) >= z]:
    print("The sublist showing triangular inequality: \n", x)

ผลลัพธ์

The sublist showing triangular inequality: [6, 8, 9]