问题遇到的现象和发生背景
列表推导式转化为正常的for循环就会报错,在运行for循环代码时会报错(RuntimeError: dictionary changed size during iteration)难道是在使用列表推导式时条件成立没有给vol2赋值?等待列表推导式结束才给vol2赋值?
用代码块功能插入代码,请勿粘贴截图
volumeA = 100
volumeB = 20
volumeC = 10
#
vol1 = []
vol2 = []
c=[]
vol1.extend((volumeA, volumeB, volumeC))
#
# print(globals().items())
#
# vol2 += [val for name, val in globals().items() if name.startswith('volume')]#列表推导式可以正常执行
#
for name,val in globals().items():#转化为for循环写法就会报错(RuntimeError: dictionary changed size during iteration)
if name.startswith('volume'):
vol2+=c.append(val)
运行结果及报错内容
我的解答思路和尝试过的方法
将全局变量赋予一个对象再去for循环得到该对象的里的key和value但是还会报错
我想要达到的结果
将列表推导式转换为for循环的写法,列表推导式的执行顺序和for循环有区别?求解答