Dus*_*rns 7 python for-loop list
我正在用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.
Run Code Online (Sandbox Code Playgroud)
现在,这可以很好地显示每个测试分数等同于分数点.但是,稍后在函数中我需要计算每个等级点值的平均值.所以,我实际上想要将等级点值分配给当时通过for循环传递的特定变量.因此,当score1通过for循环,并且确定了适当的成绩点时,我如何才能将该成绩点实际分配给score1,然后将其分配给score2,等等,因为它们通过循环?
我希望这会使问题清楚.Python本身没有这种能力似乎很愚蠢,因为如果不是这样你将无法重新定义通过for循环传递的任何变量,如果它是正在传递的列表的一部分.
nin*_*cko 14
"Python似乎没有这种能力似乎很愚蠢,因为如果不是这样你将无法重新定义通过for循环传递的任何变量,如果它是正在传递的列表的一部分." - 这就是大多数编程语言的工作方式.允许这种能力会很糟糕,因为它会产生一种称为副作用的东西,这会使代码变得迟钝.
此外,这是一个常见的编程缺陷,因为您应该使用变量名称保存数据:请参阅http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html(特别是类似问题的列表;即使您没有处理变量名字,你至少试图处理变量名称空间).补救措施是在"更高一级"工作:在这种情况下的列表或集合.这就是你原来的问题不合理的原因.(某些版本的python会让你破解locals()字典,但这是不受支持和无证件的行为和非常差的风格.)
但是你可以强制python使用这样的副作用:
scores = [99.1, 78.3, etc.]
for i,score in enumerate(scores):
scores[i] = int(score)
Run Code Online (Sandbox Code Playgroud)
以上将在scores阵列中将得分降低.然而,正确的方法(除非你正在使用数以亿计的元素)是重新创建scores数组,如下所示:
scores = [...]
roundedScores = [int(score) for score in scores]
Run Code Online (Sandbox Code Playgroud)
如果你有很多想做的事情:
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
Run Code Online (Sandbox Code Playgroud)
旁注:如果你正在进行浮点计算,你应该from __future__ import division或者使用python3,或者float(...)显式地转换.
如果你真的想修改传入的内容,可以传入一个可变对象.您传入的数字是不可变对象的实例,但例如,如果您有:
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
Run Code Online (Sandbox Code Playgroud)
这仍然是一种非功能性的做事方式,因此容易产生副作用引起的所有问题.