添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
暴走的烤地瓜  ·  json.decoder.JSONDecod ...·  5 天前    · 
温柔的汽水  ·  Executable `python` ...·  9 小时前    · 
善良的荔枝  ·  V9 Issue - Husky ...·  9 小时前    · 
旅行中的凉茶  ·  What I wish I knew ...·  9 小时前    · 
安静的莲藕  ·  [论文评述] Toward ...·  6 月前    · 
酷酷的海豚  ·  Set-Cookie - HTTP | MDN·  1 年前    · 
怕考试的日光灯  ·  INFINITI signals ...·  2 年前    · 

Python的For Loops在两个数字之间有一个冒号

3 人不认可

用冒号代替逗号的for循环到底有什么作用?我有一个列表和一个for循环,打印列表中的所有项目。 如果这真的很简单,我很抱歉,但我曾试图在网上找到答案,而且我对Python有点陌生。

import requests from bs4 import BeautifulSoup
page = requests.get("https://talksport.com/football/572055/") soup = BeautifulSoup(page.content, 'html.parser')
clubs = soup.findAll("h3")
for club in clubs[17:-2]:
   # do something
    
5 个评论
请向我们展示一些代码和你目前所做的尝试
你是说 clubs[17:-2] ?这与循环没有直接关系,而是一种只选择序列 clubs 的某些部分的方法。这被称为 slicing .
这是否回答了你的问题? 了解分片符号
I think you should check this .
python
for-loop
sam__pyle
sam__pyle
发布于 2020-06-03
1 个回答
Fredrik Nilsson
Fredrik Nilsson
发布于 2020-06-03
已采纳
0 人赞同

冒号与for循环无关,它只是对一个列表进行切分。我给你举个例子。

比方说,你有一个这样的清单。

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

当你对名单进行切分时,你只得到你要求的那部分名单,比如说。

my_list[0] # This is the first element of the list
my_list[-1] # This is the last element of the list

你可以像这样把这些与冒号结合起来。

my_list[2:5] # The elements between index 2 and 5

在这种情况下,这将是

[3, 4, 5]

在你的具体案例中。

clubs[17:-2] # The elements between index 17 and the second to last index.

由于我不知道你的名单里有什么,我将用我的名单举一个类似的例子。

my_list[4:-2]

Which returns

[5, 6, 7, 8]