现在我知道在迭代循环期间修改列表是不安全的.但是,假设我有一个字符串列表,我想自己去除字符串.替换可变值是否算作修改?
让我们考虑这个迭代列表的代码,同时每次迭代删除一个项目:
x = list(range(5))
for i in x:
print(i)
x.pop()
Run Code Online (Sandbox Code Playgroud)
它会打印出来0, 1, 2.由于前两次迭代删除了列表中的最后两个元素,因此仅打印前三个元素.
但是如果你在dict上尝试类似的东西:
y = {i: i for i in range(5)}
for i in y:
print(i)
y.pop(i)
Run Code Online (Sandbox Code Playgroud)
它将打印0,然后提升RuntimeError: dictionary changed size during iteration,因为我们正在迭代它时从字典中删除一个键.
当然,在迭代期间修改列表是不好的.但是为什么RuntimeError不像字典那样提出?这种行为有什么好的理由吗?
我有以下示例代码:
k_list = ['test', 'test1', 'test3']
def test(*args, **kwargs):
for k, value in kwargs.items():
if k in k_list:
print("Popping k = ", k)
kwargs.pop(k, None)
print("Remaining KWARGS:", kwargs.items())
test(test='test', test1='test1', test2='test2', test3='test3')
Run Code Online (Sandbox Code Playgroud)
在Python 2.7.13中,这完全可以打印出我所期望的内容,并且仍然在kwargs:
('Popping k = ', 'test')
('Popping k = ', 'test1')
('Popping k = ', 'test3')
('Remaining KWARGS:', [('test2', 'test2')])
Run Code Online (Sandbox Code Playgroud)
但是,在Python 3.6.1中,此操作失败:
Popping k = test
Traceback (most recent call last):
File "test1.py", line 11, in <module>
test(test='test', test1='test1', test2='test2', test3='test3')
File "test1.py", line 5, …Run Code Online (Sandbox Code Playgroud)