ภาพรวม
จาก 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']
คำอธิบาย
| Index | w | e | e | k |
|---|---|---|---|---|
| week | w | e | e | k |
| seek | s | e | e | k |
| beek | b | e | e | k |
| reek | r | e | e | k |
| meek | m | e | e | k |
| peek | p | e | e | k |
| 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