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

โปรแกรม Python ดึงสมาชิกที่เป็นเลขหลักเดียว (Mono-digit Elements)


เมื่อต้องการดึงสมาชิกที่เป็นเลขหลักเดียว (mono-digit) ใช้ list comprehension และตัวดำเนินการ 'all'

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

ตัวอย่าง

my_list = [863, 1, 463, "pyt", 782, 241, "is", 639, 4, "fun"] 
print("The list is :") 
print(my_list) 
my_result = [index for index in my_list if all(str(element) == str(index)[0] for element in str(index))] 
print("The result is :") 
print(my_result)

ผลลัพธ์

The list is : [863, 1, 463, 'pyt', 782, 241, 'is', 639, 4, 'fun'] 
The result is : [1, 4]

คำอธิบาย

  • กำหนดลิสต์และแสดงผล
  • ใช้ list comprehension วนลูป แปลงแต่ละ element เป็นลิสต์ เปรียบเทียบกับตัวแรก
  • แปลงเป็นลิสต์
  • กำหนดให้ตัวแปร
  • แสดงผลลัพธ์บนคอนโซล