【发布时间】:2016-03-10 20:10:36
【问题描述】:
我正在尝试编写一个函数来删除 Python 列表中的第一项。这是我尝试过的。当我调用函数时,为什么 remove_first_wrong 不改变 l ?当我在主函数中执行列表切片方法时,为什么它会起作用?
def remove_first_wrong(lst):
lst = lst[1:]
def remove_first_right(lst):
lst.pop(0)
if __name__ == '__main__':
l = [1, 2, 3, 4, 5]
remove_first_wrong(l)
print(l)
l_2 = [1, 2, 3, 4, 5]
remove_first_right(l_2)
print(l_2)
# Why does this work and remove_first_wrong doesn't?
l_3 = [1, 2, 3, 4, 5]
l_3 = l_3[1:]
print(l_3)
【问题讨论】:
-
@pigletfly:混入了一些名称与引用的混淆。
-
最好是返回值而不是就地编码,它允许使用更少的临时变量来实现更多动态类型的短代码。
标签: python