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

Python – หาตำแหน่งตัวอักษรของคำที่ K จากลิสต์สตริง

เมื่อต้องการหาตำแหน่งตัวอักษร (character position) ของคำที่ K จากลิสต์สตริง สามารถใช้ list comprehension ร่วมกับ enumerate() ได้

ตัวอย่าง

my_list = ["python", "is", "fun", "to", "learn"]
print("The list is :")
print(my_list)
K = 15
print("The value of K is :")
print(K)
my_result = [element[0] for sub in enumerate(my_list) for element in enumerate(sub[1])]
my_result = my_result[K]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : ['python', 'is', 'fun', 'to', 'learn']
The value of K is : 15
The result is : 2

คำอธิบาย

  • กำหนดลิสต์สตริงและค่า K (ตำแหน่งตัวอักษรที่ต้องการ นับจาก 0 รวมทุกคำ)

  • ใช้ list comprehension แบบ nested กับ enumerate() สร้างลิสต์ของ (ดัชนีในคำ, ตัวอักษร) ของทุกคำในลิสต์

  • ดึงสมาชิกที่ K ของลิสต์ที่สร้างได้ (เป็น tuple) แล้วเอาเฉพาะดัชนี (element[0])

  • แสดงผลลัพธ์ตำแหน่งตัวอักษร