python中[:]是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39241529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:02:30  来源:igfitidea点击:

What is the meaning of [:] in python

pythonpython-2.7web-scrapingbeautifulsoup

提问by Sourav

What does the line del taglist[:]do in the code below?

del taglist[:]下面的代码中的行有什么作用?

import urllib
from bs4 import BeautifulSoup
taglist=list()
url=raw_input("Enter URL: ")
count=int(raw_input("Enter count:"))
position=int(raw_input("Enter position:"))
for i in range(count):
    print "Retrieving:",url
    html=urllib.urlopen(url).read()
    soup=BeautifulSoup(html)
    tags=soup('a')
    for tag in tags:
        taglist.append(tag)
    url = taglist[position-1].get('href', None)
    del taglist[:]
print "Retrieving:",url

The question is "write a Python program that expands on http://www.pythonlearn.com/code/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position relative to the first name in the list, follow that link and repeat the process a number of times and report the last name you find". Sample problem: Start at http://python-data.dr-chuck.net/known_by_Fikret.htmlFind the link at position 3 (the first name is 1). Follow that link. Repeat this process 4 times. The answer is the last name that you retrieve. Sequence of names: Fikret Montgomery Mhairade Butchi Anayah Last name in sequence: Anayah

问题是“编写一个在http://www.pythonlearn.com/code/urllinks.py上扩展的 Python 程序。该程序将使用 urllib 从下面的数据文件中读取 HTML,从锚点中提取 href= vaues标签,扫描与列表中名字相关的特定位置的标签,点击该链接并重复该过程多次并报告您找到的姓氏”。示例问题:从http://python-data.dr-chuck.net/known_by_Fikret.html开始, 在位置 3(名字为 1)处找到链接。按照那个链接。重复此过程 4 次。答案是您检索到的姓氏。姓名顺序:Fikret Montgomery Mhairade Butchi Anayah 姓氏顺序:Anayah

回答by khazhyk

[:]is the array slice syntax for every element in the array.

[:]是数组中每个元素的数组切片语法。

This answer here goes more in depth of the general uses: Explain Python's slice notation

此处的答案更深入地介绍了一般用途:解释 Python 的切片符号

del arr # Deletes the array itself
del arr[:]  # Deletes all the elements in the array
del arr[2]  # Deletes the second element in the array
del arr[1:]  # etc..