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

Python – หาตัวอักษรที่เหมือนกันในตำแหน่งเดียวกัน (Common Characters at Same Index) ของ List of Strings

ภาพรวม

จาก list ของสตริง ให้หาตัวอักษรที่ตรงกัน ทุกสตริง ใน ตำแหน่งเดียวกัน (index เดียวกัน)

ตัวอย่างโค้ด


my_list = ["week", "seek", "beek", "reek", "meek", "peek"]
print("The list is:", my_list)

# หาความยาวสตริงสั้นที่สุด
min_length = min(len(s) for s in my_list)

my_result = []
for i in range(min_length):
    # ตรวจสอบว่าทุกสตริงมีตัวอักษรเดียวกันที่ index i
    if all(s[i] == my_list[0][i] for s in my_list):
        my_result.append(my_list[0][i])

print("The result is:", my_result)

ผลลัพธ์

The list is: ['week', 'seek', 'beek', 'reek', 'meek', 'peek']
The result is: ['e', 'e', 'k']

คำอธิบาย

Indexweek
weekweek
seekseek
beekbeek
reekreek
meekmeek
peekpeek
Common✗✓ e✓ e✓ k

วิธีเขียนสั้นๆ (Pythonic)


# ใช้ zip(*) transpose rows->columns
my_result = [chars[0] for chars in zip(*my_list) if all(c == chars[0] for c in chars)]

# หรือใช้ set
my_result = [chars[0] for chars in zip(*my_list) if len(set(chars)) == 1]

ประยุกต์ใช้

  • หา common prefix (ใช้ takewhile)
  • Sequence alignment ใน bioinformatics
  • ตรวจสอบ consistency ของ fixed-width records