生成按词法顺序排列的字母表的Python程序
先决条件: chr()
以下方法解释了如何使用 chr() 方法动态生成具有词汇(字母)顺序字母的Python列表。
方法:
两种方法的核心概念几乎相同,只是实现方式不同:
- 验证字母列表的大小(大小 = 26)。
- 如果 size>26,则更改为 26。
- 如果 size≤0,则函数没有任何意义,为了使其有意义,将 size 设置为 26。
- 使用 chr() 使用以下任何方法生成列表。
方法一:使用循环
Python3
# function to get the list of alphabets
def generateAlphabetListDynamically(size = 26):
size = 26 if (size > 26 or size <= 0) else size
# Empty list
alphabetList = []
# Looping from 0 to required size
for i in range(size):
alphabetList.append(chr(65 + i))
# return the generated list
return alphabetList
alphabetList = generateAlphabetListDynamically()
print('The alphabets in the list are:', *alphabetList)
Python3
def generateAlphabetListDynamically(size=26):
size = 26 if (size > 26 or size <= 0) else size
# Here we are looping from 0 to upto specified size
# 65 is added because it is ascii equivalent of 'A'
alphabetList = [chr(i+65) for i in range(size)]
# returning the list
return alphabetList
# Calling the function to get the alphabets
alphabetList = generateAlphabetListDynamically()
print('The alphabets in the list are:', *alphabetList)
输出:
The alphabets in the list are: 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
方法 2:使用列表理解
蟒蛇3
def generateAlphabetListDynamically(size=26):
size = 26 if (size > 26 or size <= 0) else size
# Here we are looping from 0 to upto specified size
# 65 is added because it is ascii equivalent of 'A'
alphabetList = [chr(i+65) for i in range(size)]
# returning the list
return alphabetList
# Calling the function to get the alphabets
alphabetList = generateAlphabetListDynamically()
print('The alphabets in the list are:', *alphabetList)
输出:
The alphabets in the list are: 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