将列表中的项目替换为其他列表中的项目

2024-09-30 04:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为用户的加权平均绩点创建一个计算器。我正在使用PyautoGUI询问用户的成绩和他们所上的课的类型。但我希望能够接受用户输入,并将其重新映射到不同的值。你知道吗

class GPA():
    grades = []
    classtypes = []

    your_format = confirm(text='Choose your grade format: ', title='', 
    buttons=['LETTERS', 'PERCENTAGE', 'QUIT'])

    classnum = int(prompt("Enter the number of classes you have: "))

    for i in range(classnum):
        grade = prompt(text='Enter your grade for the course 
:'.format(name)).lower()
    classtype = prompt(text='Enter the type of Course (Ex. Regular, AP, Honors): ').lower()

    classtypes.append(classtype)
    grades.append(grade)

    def __init__(self):
        self.gradeMap = {'a+': 4.0, 'a': 4.0, 'a-': 3.7, 'b+': 3.3, 'b': 3.0,'b-': 2.7,
         'c+': 2.3, 'c': 2.0, 'c-': 1.7, 'd+': 1.3, 'd': 1.0, 'f': 0.0}
        self.weightMap = {'advanced placement': 1.0, 'ap': 1.0, 'honors': 0.5,'regular': 0.0}

Tags: ofthetext用户selfformatforyour
2条回答

可以就地替换列表中的项。你知道吗

for grade in gradeList:
    if type is "PERCENTAGE":
       grade = grade × some_factor  # use your logic
    elif type is "LETTERS":
       grade="some other logic"

根据您定义的gradeMap字典,您可以使用所谓的list comprehension做一些事情。你知道吗

我所说的使用Python解释器完成的示例:

>>> grades = ['a', 'c-', 'c']
>>> gradeMap = {'a+': 4.0, 'a': 4.0, 'a-': 3.7, 'b+': 3.3, 'b': 3.0,'b-': 2.7,
...             'c+': 2.3, 'c': 2.0, 'c-': 1.7, 'd+': 1.3, 'd': 1.0, 'f': 0.0}
>>> [gradeMap[grade] for grade in grades] #here's the list comprehension
[4.0, 1.7, 2.0]

我认为这种方法的缺点可能是确保用户只给你在gradeMap中定义的分数,否则它会给你一个KeyError。你知道吗

另一种选择是使用^{}map稍有不同,它需要一个函数和一个输入列表,然后将该函数应用于输入列表。你知道吗

一个非常简单的函数只适用于几个等级的示例:

>>> def convert_grade_to_points(grade):
...   if grade == 'a':
...     return 4.0
...   elif grade == 'b':
...     return 3.0
...   else:
...     return 0
... 
>>> grades = ['a', 'b', 'b']
>>> map(convert_grade_to_points, grades)
[4.0, 3.0, 3.0]

这也有我前面提到的缺点,即您定义的函数必须处理用户输入无效等级的情况。你知道吗

相关问题 更多 >

    热门问题