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

Python – กรอง Tuple ที่มีเฉพาะจำนวนเต็ม


เมื่อต้องการกรอง tuple ที่มีเฉพาะจำนวนเต็ม ใช้การวนลูปง่าย ตัวดำเนินการ 'not' และเมธอด 'isinstance'

ตัวอย่าง

สาธิตด้านล่าง:

my_tuple = [(14, 25, "Python"), (5, 6), (3, ), ("cool", )] 
print("The tuple is :") 
print(my_tuple) 
my_result = [] 
for sub in my_tuple: 
    temp = True 
    for element in sub: 
        if not isinstance(element, int): 
            temp = False 
            break 
    if temp : 
        my_result.append(sub) 
print("The result is :") 
print(my_result)

ผลลัพธ์

The tuple is : [(14, 25, 'Python'), (5, 6), (3,), ('cool',)] 
The result is : [(5, 6), (3,)]

คำอธิบาย

  • กำหนดลิสต์ของ tuple และแสดงผล
  • สร้างลิสต์ว่าง
  • วนลูปลิสต์ ใช้ 'isinstance' ตรวจสอบว่า element เป็น integer
  • ถ้าไม่ใช่ กำหนด Boolean = False break ลูป
  • ขึ้นกับค่า Boolean append element เข้าไปในลิสต์ว่าง
  • แสดงผลลัพธ์บนคอนโซล