Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python - 알파벳으로 목록을 초기화하는 방법

<시간/>

목록으로 작업하는 동안 때때로 영어 알파벳 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']