Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么列表的长度不变?_Python_List - Fatal编程技术网

Python 为什么列表的长度不变?

Python 为什么列表的长度不变?,python,list,Python,List,这是我的在线课程代码,我不知道为什么列表的长度仍然是1 tags = soup('a') for tag in tags: tag = tag.get('href', None) tag.strip() tag = str(tag) tag.split() names = [] names.append(tag) print names print len(names) 它还给我们: [''] 1. [''] 1因为此行在fo

这是我的在线课程代码,我不知道为什么列表的长度仍然是1

tags = soup('a')

for tag in tags: 
    tag = tag.get('href', None)
    tag.strip()
    tag = str(tag)
    tag.split()
    names = []
    names.append(tag)
    print names
    print len(names)
它还给我们: [''] 1. ['']
1

因为此行在for循环内:

names = []
这意味着在循环的每次迭代中,
names
被重置为
[]
。你应该把那一行放在for循环之前

tags = soup('a')
names = []
for tag in tags: 
    tag = tag.get('href', None)
    tag.strip()
    tag = str(tag)
    tag.split()
    names.append(tag)
    print names
    print len(names)