在使用列表时,有时我们希望使用英文字母az初始化列表。在某些应用程序中,这是必不可少的工具。
# 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']