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

Python - วิธีการสร้างลิสต์อักษรอังกฤษ a-z

ขณะทำงานกับลิสต์ บางครั้งเราต้องการสร้างลิสต์ที่มีอักษรอังกฤษ a-z ครบ ซึ่งเป็น utility ที่จำเป็นในบางแอปพลิเคชัน

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

1. ใช้วิธี Naive (Loop ธรรมดา)

# เริ่มต้นลิสต์ว่าง
test_list = []
print("Initial list :", str(test_list))

# ใช้ loop ทั่วไป
alpha = 'a'
for i in range(0, 26):
    test_list.append(alpha)
    alpha = chr(ord(alpha) + 1)

print("List after insertion :", str(test_list))

2. ใช้ List Comprehension (แนะนำ)

test_list = []
print("Initial list :", str(test_list))

# ใช้ list comprehension
test_list = [chr(x) for x in range(ord('a'), ord('z') + 1)]

print("List after insertion :", str(test_list))

3. ใช้ map()

test_list = []
print("Initial list :", str(test_list))

# ใช้ map()
test_list = list(map(chr, range(97, 123)))

print("List after insertion :", str(test_list))

4. ใช้โมดูล string (ง่ายที่สุด)


import string

test_list = []
print("Initial list :", str(test_list))

# ใช้ string.ascii_lowercase
test_list = list(string.ascii_lowercase)

print("List after insertion :", str(test_list))

ผลลัพธ์


['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

สรุป

  • string.ascii_lowercase - วิธีที่สะดวก เร็ว และอ่านง่ายที่สุด (แนะนำ)
  • List Comprehension - ยืดหยุ่น ได้ผลลัพธ์เดียวกัน เข้าใจง่าย
  • map() - สไตล์ functional programming
  • Naive loop - เข้าใจตรรกะพื้นฐาน แต่โค้ดยาวกว่า

เพิ่มเติม


# ตัวพิมพใหญ่
list(string.ascii_uppercase)  # ['A', 'B', ..., 'Z']

# ทั้งสองชุด
list(string.ascii_letters)    # ['a', 'b', ..., 'z', 'A', 'B', ..., 'Z']