我在python中使用list时遇到了一个问题
with open('test.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
line = [l.rstrip('\n') for l in lines[:2]]
print(line[0])
ll = []
for lin in lines[2:]:
ll.append(lin)
break
print(line[0])
结果是:
0;;no2;;the third part3;;the fourth part4
0;;no2;;the third part3;;the fourth part4
但是当我将变量lin转换为行时(提到的名称相同)
with open('test.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
line = [l.rstrip('\n') for l in lines[:2]]
print(line[0])
ll = []
for line in lines[2:]:
ll.append(line)
break
print(line[0])
结果是:
0;;no2;;the third part3;;the fourth part4
0
很明显,当共享相同的变量名时,行的值在for循环期间发生了变化
这与列表的存储方式无关。for循环变量的作用域无法按预期方式工作
这是预期的行为。与其他语言不同,python不会为循环创建新的作用域
下面是关于这个主题的更多细节:Scoping in Python 'for' loops
相关问题 更多 >
编程相关推荐