python中for循环的作用域是如何工作的?

2024-09-28 01:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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循环期间发生了变化


Tags: theinforwithlineopenlinesprint
1条回答
网友
1楼 · 发布于 2024-09-28 01:29:47

这与列表的存储方式无关。for循环变量的作用域无法按预期方式工作

It apparently shows that the value of line has been change during the for loop when sharing the same variable name.

这是预期的行为。与其他语言不同,python不会为循环创建新的作用域

下面是关于这个主题的更多细节:Scoping in Python 'for' loops

相关问题 更多 >

    热门问题