鱼C论坛

 找回密码
 立即注册
查看: 2772|回复: 10

新手提问

[复制链接]
发表于 2016-11-13 09:13:51 | 显示全部楼层 |阅读模式
1鱼币

有关列表索引的一个问题

>>> list1
[123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456]
>>> list1.index(123)
0
>>> list1.index(123,3,7)
4
index后面第二个参数3是从列表第四个元素开始,后面的7是神马意思,是到列表第七个元素结束,还是从第四个元素开始数七个元素?而下面我把7改成5后返回值依然是4,真的搞不明白?如下,烦请解答,谢谢!
>>> list1.index(123,3,5)
4

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-13 11:56:04 | 显示全部楼层
index(...)
|      L.index(value, [start, [stop]]) -> integer -- return first index of value.
|      Raises ValueError if the value is not present.

不然你想返回几。。
list1[3:5]里包含123, 且处于全列表的第4个位置,就返回了4。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-11-13 12:09:40 | 显示全部楼层
wei_Y 发表于 2016-11-13 11:56
index(...)
|      L.index(value, [start, [stop]]) -> integer -- return first index of value.
|   ...

>>> list1.index(123,3,7)
4
那为什么把index第三个参数改成7返回值也是4? index后面第三个参数是什么意思?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-13 12:18:49 | 显示全部楼层
Andrew103496137 发表于 2016-11-13 12:09
>>> list1.index(123,3,7)
4
那为什么把index第三个参数改成7返回值也是4? index后面第三个参数是什么 ...

list1[3:7]中包含123,且这个123处在整个列表的第4个位置,所以返回4.
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-13 12:32:12 | 显示全部楼层
楼主我跟你说下吧
首先在idle里查看列表中的index()方法,如下:
1.jpg
  1. Help on built-in function index:

  2. index(...) method of builtins.list instance
  3.     L.index(value, [start, [stop]]) -> integer -- return first index of value.
  4.     Raises ValueError if the value is not present.
复制代码

第一个参数是你要在列表中查询的值,第二个参数是你要开始查找的位置,第三个参数是你要查找的终止位置,该方法返回值为一个整数

return first index of value,注意注意楼主,关键字“first”,返回的是值出现的第一个位置,所以说你不管你第三个参数是几,它只返回你给它开始位置到终止位置这个值第一次出现的位置,所以值总是4,这是它第一次出现,文档已经很清楚说明了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-13 16:20:04 | 显示全部楼层
索引3开始,索引7结束
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-11-13 17:09:21 | 显示全部楼层
三少爷 发表于 2016-11-13 16:20
索引3开始,索引7结束

非常感谢各位的解答,谢谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-14 11:26:43 | 显示全部楼层
list.index(参数1,参数2,参数3),意思是指找出在指定切片内(参数2到参数3之间)参数1第一次出现的位置,所以这来两个的答案都是4
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-14 15:28:42 | 显示全部楼层
返回的是第一个查到的索引吧
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-16 11:53:19 | 显示全部楼层
list.index(value, start, end)
value :是要查找的值
start:  是在list中下标为start处开始查找(注:意:包含下标为start的元素)
end:   是在list中下标为end 处结束查找(注意: 不包含下标为end的元素)
如果还是不明白,那就@我吧
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-11-16 11:55:18 | 显示全部楼层
再发一条
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-23 20:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表