“Python 不具备这种功能似乎很愚蠢,因为如果没有这种功能,你将无法重新定义通过 for 循环传递的任何变量(如果它是正在传递的列表的一部分)。”- 这就是大多数编程语言的工作原理。允许这种功能是很糟糕的,因为它会产生副作用,从而使代码变得迟钝。
此外,这是一个常见的编程陷阱,因为您应该将数据保留在变量名称之外: see http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html 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)
以上将把分数向下舍入scores
大批。这正确的方法然而,要做到这一点(除非您正在使用数亿个元素)是重新创建scores
像这样的数组:
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
旁注:如果你正在进行浮点计算,你应该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
这仍然是一种非功能性的做事方式,因此容易出现副作用引起的所有问题。