Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何更改以列表形式馈入for循环的变量_Python_List_For Loop - Fatal编程技术网

Python 如何更改以列表形式馈入for循环的变量

Python 如何更改以列表形式馈入for循环的变量,python,list,for-loop,Python,List,For Loop,我正在用Python编写一个基本程序,提示用户输入5个测试分数。然后,程序将每个测试分数转换为一个分数点(即4.0、3.0、2.0…),然后取这些数字的平均值 我为每个测试分数分配了自己的变量,并将它们输入到for循环中,如下所示: for num in [score1, score2, score3, score4, score5]: if num >= 90 print('Your test score is a 4.0) elif num < 90 a

我正在用Python编写一个基本程序,提示用户输入5个测试分数。然后,程序将每个测试分数转换为一个分数点(即4.0、3.0、2.0…),然后取这些数字的平均值

我为每个测试分数分配了自己的变量,并将它们输入到for循环中,如下所示:

for num in [score1, score2, score3, score4, score5]:
   if num >= 90
       print('Your test score is a 4.0)
   elif num < 90 and >= 80
   .
   .
   and so on for each grade point.
对于[score1、score2、score3、score4、score5]中的num:
如果num>=90
打印('您的考试分数为4.0分)
elif num<90且>=80
.
.
等等,每一个分数。
现在,这可以很好地显示每个测试分数相当于分数。但是,在函数的后面部分,我需要计算每个坡度点值的平均值。所以,我实际上想给当时通过for循环传递的特定变量分配一个grade point值。所以,当分数1通过for循环,并且确定了相应的分数点时,我如何实际地将该分数点分配给分数1,然后在分数2通过循环时分配给分数2等等

我希望这能把问题弄清楚。Python不具备这种功能似乎很愚蠢,因为如果不具备这种功能,您将无法重新定义通过for循环传递的任何变量,如果它是正在传递的列表的一部分。

“Python不具备这种功能似乎很愚蠢,因为如果不具备这种功能,您将无法重新定义通过for循环传递的任何变量(如果它是正在传递的列表的一部分)。“-这就是大多数编程语言的工作方式。允许这种功能是不好的,因为它会产生所谓的副作用,使代码变得迟钝

此外,这是一个常见的编程陷阱,因为您应该将数据排除在变量名称之外。:请参阅(特别是类似问题的列表;即使您没有处理变量名称,您至少也在尝试处理变量名称空间)。补救办法是在“更高一级”上工作:在这种情况下是一个列表或集合。这就是你原来的问题不合理的原因。(某些版本的python允许您破解
locals()
字典,但这是不受支持的、未记录的行为,而且样式非常糟糕。)


但是,您可以强制python使用以下副作用:

scores = [99.1, 78.3, etc.]
for i,score in enumerate(scores):
    scores[i] = int(score)
以上内容将在
分数
数组中向下取整分数。但是,正确的方法是重新创建
分数
数组,如下所示:

scores = [...]
roundedScores = [int(score) for score in scores]
如果您有很多事情要做,以获得分数:

scores = [..., ..., ...]

def processScores(scores):
    '''Grades on a curve, where top score = 100%'''
    theTopScore = max(scores)

    def processScore(score, topScore):
        return 100-topScore+score

    newScores = [processScore(s,theTopScore) for s in scores]
    return newScores
旁注:如果你在进行浮点计算,你应该明确地从uuu future uuu导入division或使用python3,或强制转换到
浮点(…)


如果您确实想修改传入的内容,可以传入一个可变对象。您传递的数字是不可变对象的实例,但如果您有:

class Score(object):
    def __init__(self, points):
        self.points = points
    def __repr__(self):
        return 'Score({})'.format(self.points)

scores = [Score(i) for i in [99.1, 78.3, ...]]
for s in scores:
    s.points += 5  # adds 5 points to each score

这仍然是一种非功能性的做事方式,因此容易出现副作用引起的所有问题。

问题在于,当你写这篇文章时:

for num in [score1, score2, score3, score4, score5]:
所发生的事情是,您正在创建一个列表,其中包含五个元素,这些元素在开始迭代时由score1到score5的值定义。更改其中一个元素不会更改原始变量,因为您已经创建了一个包含这些值的副本的列表

如果运行以下脚本:

score1 = 2
score2 = 3

for num in [score1, score2]:
    num = 1

for num in [score1, score2]:
    print(num)
您将看到,更改包含实际变量副本的列表中的每个值实际上不会更改原始变量的值。为了更好地理解这一点,您可以考虑查找“通过引用”和“按值传递”的区别。 对于这个特殊的问题,我建议首先将您希望能够修改的变量放在一个列表中,然后迭代该列表,而不是包含这些变量副本的列表

# Take the list of grade as input, assume list is not empty
def convertGrade(myGrades):
    myResult = [] # List that store the new grade
    for grade in myGrades:
        gpa = (grade / 20) -1
        # Depending on how many deciaml you want
        gpa = round(gpa, 1)
        myResult.append(gpa)
    return myResult

# The list of grades, can be more than 5 if you want to
grades = [88.3, 93.6, 50.2, 70.2, 80.5]
convertedGrades = convertGrade(grades)
print(convertedGrades)

total = 0
# If you want the average of them
for grade in convertedGrades:
    total += grade # add each grade into the total

average = total / len(convertedGrades)
print('Average GPA is:', average)
我想这可能是你想要的,这类事情很简单,所以python希望你自己编写,我不知道你的意思是python应该带有GPA转换函数,你当然可以轻松编写一个。如果您只需要整数(我不确定,因为GPA通常带有小数点),那么可以使用int(),或者在追加之前将其四舍五入为0

输出:

[3.4, 3.7, 1.5, 2.5, 3.0]
Average GPA is: 2.82

第一条规则:当处理一组类似的项目时,不要使用一组命名变量——使用数组(列表、集合、字典,任何最有意义的)

第二条规则:除非你真的需要空间,否则不要用这种方式覆盖你的变量——你试图让一个标签(变量名)代表两个不同的东西(原始标记和/或gpa)。这使得调试非常讨厌

def get_marks():
    marks = []
    while True:
        inp = raw_input("Type in the next mark (just hit <Enter> to quit): ")
        try:
            marks.append(float(inp))
        except ValueError:
            return marks

def gpa(mark):
    if mark >= 90.0:
        return 4.0
    elif mark >= 80.0:
        return 3.0
    elif mark >= 70.0:
        return 2.0
    elif mark >= 60.0:
        return 1.0
    else:
        return 0.0

def average(ls):
    return sum(ls)/len(ls)

def main():
    marks = get_marks()
    grades = [gpa(mark) for mark in marks]

    print("Average mark is {}".format(average(marks)))
    print("Average grade is {}".format(average(grades)))

if __name__=="__main__":
    main()
def get_marks():
分数=[]
尽管如此:
inp=原始输入(“输入下一个标记(点击退出):”)
尝试:
标记。附加(浮动(inp))
除值错误外:
返回标记
def gpa(标记):
如果标记>=90.0:
返回4.0
elif标记>=80.0:
返回3.0
elif标记>=70.0:
返回2.0
elif标记>=60.0:
返回1.0
其他:
返回0.0
def平均值(ls):
返回金额(ls)/长度(ls)
def main():
marks=获取_标记()
成绩=[分入分数的gpa(分数)]
打印(“平均标记为{}”。格式(平均(标记)))
打印(“平均分数为{}”。格式(平均(分数)))
如果名称=“\uuuuu main\uuuuuuuu”:
main()
“Python不具备这种功能似乎很愚蠢,因为如果不具备这种功能,您将无法重新定义通过for循环传递的任何变量,如果它是正在传递的列表的一部分。”-这就是大多数编程语言的工作方式。允许这种能力是不好的,因为它会产生所谓的副作用,这会使