如果你的目的是以某种方式改变一个不可变的值,这将是最好的。
def add_one(value):
return value + 1
def main():
# your code moved to a function, to avoid these variables inadvertently becoming globals
item = 1
# update item with the function result
item = add_one(item)
print("item is => ", item)
if __name__ == '__main__':
main()
从你的例子来看,你似乎想更新一个列表,列表中的每个项目都递增1,你可以用同样的方法来做。
def add_one_all(values):
return [values + 1 for values in values]
def main():
items = [1, 4, 9]
# update items with the function result
items = add_one_all(items)
print("items are => ", items)
if __name__ == '__main__':
main()
然而,由于列表是可变的,你可以可以从一个函数中更新它,通过对列表进行原地修改。
def add_one_all_inplace(values: list = None):
if values is not None:
for i in range(len(values)):
values[i] += 1
def main():
items = [1, 4, 9]
# update the content of items
add_one_all_inplace(items)
print("items are => ", items)
if __name__ == '__main__':
main()
后一种解决方案的优点是不创建新的列表,如果你需要非常节省空间,或者只对一个非常大的列表做一些修改,这可能是比较好的选择--不过你的例子可能更适合第二种解决方案。
请注意,在后一种情况下,你调用该函数的方式仍然无法工作。
def main():
item = 1
add_one_all_inplace([item])
包含item
的列表将被改变为[2]
,但这并不影响item
本身。传给add_one_all_inplace
的列表将只包含item
的值,而不是对它的引用。