如何更改以列表形式输入 for 循环的变量 [英] How to change variables fed into a for loop in list form

查看:43
本文介绍了如何更改以列表形式输入 for 循环的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

for num in [score1, score2, score3, score4, score5]:如果数量 >= 90print('你的考试成绩是4.0)elif 编号 <90 且 >= 80..依此类推每个年级点.

现在,这可以很好地显示每个测试分数相当于学分.但是,稍后在函数中,我需要计算每个成绩点值的平均值.所以,我实际上想为当时通过 for 循环的特定变量分配一个成绩点值.因此,当通过 for 循环传递 score1 并确定适当的成绩点时,我如何实际将该成绩点分配给 score1,然后在它们通过循环时分配给 score2,依此类推?

我希望这能说明问题.Python 没有这种能力似乎很愚蠢,因为如果没有,如果它是正在传递的列表的一部分,那么您将无法重新定义任何通过 for 循环传递的变量.

解决方案

"Python 没有这种能力似乎很愚蠢,因为如果没有,你将无法重新定义任何通过的变量一个 for 循环,如果它是正在传递的列表的一部分." - 这就是大多数编程语言的工作方式.允许这种能力是不好的,因为它会产生一种叫做副作用的东西,这会使代码变得迟钝.

此外,这是一个常见的编程陷阱,因为您应该将数据保留在变量名称之外:参见 http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html(尤其是类似问题的列表;即使您不处理变量名称,您至少也在尝试处理与变量命名空间).补救措施是在更高一级"上工作:在这种情况下是一个列表或集合.这就是为什么你原来的问题是不合理的.(某些版本的 python 会让你破解 locals() 字典,但这是不受支持和未记录的行为,而且风格很差.)

<小时>

然而,你可以强制 python 使用这样的副作用:

scores = [99.1, 78.3, etc.]对于 i,score in enumerate(scores):分数[i] = int(分数)

以上将在 scores 数组中向下舍入分数.但是,正确的方法(除非您正在处理数亿个元素)是像这样重新创建 scores 数组:

scores = [...]roundedScores = [int(score) for score in score]

如果你有很多事情想要做一个分数:

scores = [..., ..., ...]def processScores(scores):'''曲线上的成绩,其中最高分 = 100%'''theTopScore = max(scores)def processScore(score, topScore):返回 100-topScore+scorenewScores = [processScore(s,theTopScore) for s in score]返回新分数

旁注:如果你在做浮点计算,你应该from __future__ import Division 或者使用python3,或者显式转换为float(...).><小时>

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

class Score(object):def __init__(self, points):self.points = 点数def __repr__(self):返回 '​​Score({})'.format(self.points)分数 = [Score(i) for i in [99.1, 78.3, ...]]对于分数中的 s:s.points += 5 # 每分加5分

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

I am writing a basic program in Python that prompts the user to enter 5 test scores. The program will then convert each test score to a grade point (i.e. 4.0, 3.0, 2.0...), and then afterwards take the average of these numbers.

I've assigned each test score their own variable, and I'm feeding them into a for loop as follows:

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.

Now, this does fine for displaying what each test score is equivalent to grade point wise. However, later in the function I need to calculate the average of each of these grade point values. So, I'd actually like to assign a grade point value to the specific variable passed through the for loop at that time. So, when score1 is passed through the for loop, and the appropriate grade point is determined, how can I actually assign that grade point to score1, and then later for score2 and so on as they are passed through the loop?

I hope that makes the question clear. It would seem silly that Python would not have this kind of capability, because if not you wouldn't be able to redefine any variable passed through a for loop if it is part of a list that is being passed through.

解决方案

"It would seem silly that Python would not have this kind of capability, because if not you wouldn't be able to redefine any variable passed through a for loop if it is part of a list that is being passed through." - That's how most programming languages work. To allow this capability would be bad because it would create something called side-effects, which make code obtuse.

Additionally this is a common programming pitfall because you should keep data out of variable names: see http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html (especially the list of similar questions; even if you aren't dealing with variables names, you are at least trying to deal with the variable namespace). The remedy is to work at "one level higher": a list or set in this case. This is why your original question is not reasonable. (Some versions of python will let you hack the locals() dictionary, but this is unsupported and undocumented behavior and very poor style.)


You can however force python to use side-effects like so:

scores = [99.1, 78.3, etc.]
for i,score in enumerate(scores):
    scores[i] = int(score)

the above will round scores down in the scores array. The right way to do this however (unless you are working with hundreds of millions of elements) is to recreate the scores array like so:

scores = [...]
roundedScores = [int(score) for score in scores]

If you have many things you want to do to a score:

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

sidenote: If you're doing float calculations, you should from __future__ import division or use python3, or cast to float(...) explicitly.


If you really want to modify what is passed in, you can pass in a mutable object. The numbers you are passing in are instances of immutable objects, but if for example you had:

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

This would still be a non-functional way to do things, and thus prone to all the issues that side-effects cause.

这篇关于如何更改以列表形式输入 for 循环的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆