我正在尝试使用Gotcha语句来保存变量列表以进行比较。但是在我的程序结束时,我想重置此列表,使其为空,并且可以重新启动该过程。以下是我想要的一个简单示例,以及我实际得到的内容:
def append_to(element, reset, to = []):
if reset == 'reset':
to = []
return
to.append(element)
return to
my_list = append_to(12, 'Not reset')
print my_list
my_other_list = append_to(42, 'Not reset')
print my_other_list
append_to(1, 'reset')
my_list = append_to(13, 'Not reset')
print my_list
my_other_list = append_to(43, 'Not reset')
print my_other_list
这是输出:
[12]
[12, 42]
[12, 42, 13]
[12, 42, 13, 43]
所需输出:
[12]
[12, 42]
[13]
[13,43]
如何重置此列表?感谢
答案 0 :(得分:1)
您将使用del to[:]
(或3.3+上的to.clear()
)。写to = []
绑定到本地变量。
使用append
修改局部变量指向的对象;调用者也会指出这一点,这就是append
工作的原因。
答案 1 :(得分:0)
to = []
不会影响原始列表。它只是使局部变量引用新列表。
使用切片表示法或del
语句来就地清除列表。
def append_to(element, reset, to = []):
if reset == 'reset':
to[:] = []
# or del to[:]
return
to.append(element)
return to