相关疑难解决方法(0)

如何在for循环期间修改列表条目?

现在我知道在迭代循环期间修改列表是不安全的.但是,假设我有一个字符串列表,我想自己去除字符串.替换可变值是否算作修改?

python

150
推荐指数
5
解决办法
21万
查看次数

在迭代期间修改列表和字典,为什么它在dict上失败?

让我们考虑这个迭代列表的代码,同时每次迭代删除一个项目:

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不像字典那样提出?这种行为有什么好的理由吗?

python iteration dictionary loops list

29
推荐指数
2
解决办法
1441
查看次数

字典在迭代过程中更改了大小-代码在Py2中有效,而在Py3中无效

我有以下示例代码:

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)

python dictionary python-2.7 python-3.x

3
推荐指数
2
解决办法
3218
查看次数

标签 统计

python ×3

dictionary ×2

iteration ×1

list ×1

loops ×1

python-2.7 ×1

python-3.x ×1