Python – 构建成绩列表
给定一个数字,构造列表,其中包含前 N 个字符的所有可能的 Grades 组合。
Input : num = 3
Output : [‘A+’, ‘A’, ‘A-‘, ‘B+’, ‘B’, ‘B-‘, ‘C+’, ‘C’, ‘C-‘]
Explanation : All grades till C rendered in list.
Input : num = 5
Output : [‘A+’, ‘A’, ‘A-‘, ‘B+’, ‘B’, ‘B-‘, ‘C+’, ‘C’, ‘C-‘, ‘D+’, ‘D’, ‘D-‘, ‘E+’, ‘E’, ‘E-‘]
Explanation : 5 corresponds to E, hence all combinations.
方法 #1:使用列表理解 + ord()
上述功能的组合可以用来解决这个问题。在此,我们使用 ord() 执行递增和提取 ascii字符的任务,并在字符列表创建中使用列表推导。
Python3
# Python3 code to demonstrate working of
# Construct Grades List
# Using list comprehension + ord()
# initializing N
num = 4
# Using list comprehension + ord()
# each character paired to symbols and character incremented using idx
# conversion by chr + ord
res = [chr(ord('A') + idx) + sym for idx in range(num)
for sym in ['+', '', '-']]
# printing result
print("Grades List : " + str(res))
Python3
# Python3 code to demonstrate working of
# Construct Grades List
# Using join() + map() + product() + ascii_uppercase
from string import ascii_uppercase
from itertools import product
# initializing N
num = 4
# Using join() + map() + product() + ascii_uppercase
# pairing using product, map used to join characters with symbols.
res = [*map(''.join, product(ascii_uppercase[:num], ['+', '', '-']))]
# printing result
print("Grades List : " + str(res))
输出 :
Grades List : ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-']
方法 #2:使用 join() + map() + product() + ascii_uppercase
上述功能的组合可以用来解决这个问题。在此,我们使用 ascii_uppercase 执行提取 ascii字符的任务,product() 和 map() 用于执行与符号的链接,结果是在执行 all 后创建的。
Python3
# Python3 code to demonstrate working of
# Construct Grades List
# Using join() + map() + product() + ascii_uppercase
from string import ascii_uppercase
from itertools import product
# initializing N
num = 4
# Using join() + map() + product() + ascii_uppercase
# pairing using product, map used to join characters with symbols.
res = [*map(''.join, product(ascii_uppercase[:num], ['+', '', '-']))]
# printing result
print("Grades List : " + str(res))
输出 :
Grades List : ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-']