ขณะทำงานกับรายการ บางครั้งเราต้องการเริ่มต้นรายการด้วยตัวอักษรภาษาอังกฤษ a-z นี่เป็นยูทิลิตี้ที่จำเป็นในบางแอปพลิเคชัน
ตัวอย่าง
# using naive method # initializing empty list test_list = [] # printing initial list print ("Initial list : " + str(test_list)) # using naive method # for filling alphabets alpha = 'a' for i in range(0, 26): test_list.append(alpha) alpha = chr(ord(alpha) + 1) # printing resultant list print ("List after insertion : " + str(test_list)) # using list comprehension # initializing empty list test_list = [] # printing initial list print ("Initial list : " + str(test_list)) # using list comprehension # for filling alphabets test_list = [chr(x) for x in range(ord('a'), ord('z') + 1)] # printing resultant list print ("List after insertion : " + str(test_list)) # using map() # initializing empty list test_list = [] # printing initial list print ("Initial list : " + str(test_list)) # using map() # for filling alphabets test_list = list(map(chr, range(97, 123))) # printing resultant list print ("List after insertion : " + str(test_list)) # using string import string # initializing empty list test_list = [] # printing initial list print ("Initial list : " + str(test_list)) # using string # for filling alphabets test_list = list(string.ascii_lowercase) # printing resultant list print ("List after insertion : " + str(test_list))
ผลลัพธ์
Initial list : [] List after insertion : ['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'] Initial list : [] List after insertion : ['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'] Initial list : [] List after insertion : ['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'] Initial list : [] List after insertion : ['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']