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

Get First Index Values ใน Tuple of Strings Python: ดึงตัวอักษรแรกของแต่ละสตริง

ได้ Tuple ของสตริง ต้องการลิสต์ของตัวอักษรแรกแต่ละสตริง

วิธี 1: ใช้ Index ใน Generator Expression

tupA = ('Mon', 'Tue', 'Wed', 'Fri')
res = [s[0] for s in tupA]
print(res)  # ['M', 'T', 'W', 'F']

วิธี 2: ใช้ next(zip(*tupA))

tupA = ('Mon', 'Tue', 'Wed', 'Fri')
res = list(next(zip(*tupA)))
print(res)  # ['M', 'T', 'W', 'F']

คำอธิบาย

zip(*tupA) จับกลุ่มตัวอักษรตำแหน่งเดียวกัน (transpose) next(...) ดึงกลุ่มแรก (ตัวอักษรแรกทุกสตริง)