我知道索引函数的工作原理如下:
list = ['dog','cat','pizza','trump', 'computer', 'trump']
print list.index('trump')
输出为3。 但现在我希望他打印另一个特朗普'串, 来自2个物体之后。但如果我会做同样的命令:
print list.index('trump')
他将再次打印3 - 他看到的第一个特朗普。
那么如何移动'偏移'对于索引函数,所以她会检测另一个特朗普,在索引5中?
非常感谢你们!
答案 0 :(得分:5)
list.index
采取第二个开始论点:
>>> lst = ['dog','cat','pizza','trump', 'computer', 'trump']
>>> lst.index('trump') # 1st index
3
>>> lst.index('trump',4) # 2nd index
5
>>> lst.index('trump',lst.index('trump')+1) # 2nd index
5
或者,如果您想要所有索引,请使用列表推导:
>>> [idx for idx,item in enumerate(lst) if item == 'trump']
[3, 5]
答案 1 :(得分:5)
只需记下字符串出现的第一个索引,然后第二次将额外参数传递给index
:
l = ['dog','cat','pizza','trump', 'computer', 'trump']
i = l.index("trump")
print(i)
print(l.index("trump",i+1))
我明白了:
3
5
来自内联文档,您可以传递一个可选的开始&停止价值:
指数(...)
L.index(value,[start,[stop]]) - >整数 - 返回第一个值的索引。 如果值不存在,则引发ValueError。
(在一般情况下,如果值不在列表中并且相应地采取行动,则必须通过index
块来保护您对try/except ValueError
的调用。
请注意,start
可能是否定的。如果为负数,则从列表的末尾开始计算索引。
答案 2 :(得分:2)
如果您想要列表中条目的所有索引列表,您可以执行以下操作:
indices = [i for i, x in enumerate(list) if x == "key"]
答案 3 :(得分:1)
创建列表的缩短版本。
list=['dog','cat','pizza','trump', 'computer', 'trump']
print list.index('trump')
list = list[list.index('trump')+1:]
print list.index('trump')
答案 4 :(得分:1)
l = ['dog','cat','pizza','trump', 'computer', 'trump']
i = [n for n, item in enumerate(l) if item == 'trump'] #find all indices
# print the result
for n in i:
print n, l[n]
3 trump
5 trump
答案 5 :(得分:0)
试试这个...它就像魅力一样。
实际上在你的问题迭代中只执行一次,即使在for循环中它也不起作用(即使在iter
和next()
使用后也不适合我)所以我尝试了while
然后我意识到这是迭代游戏,所以将while
放在try
中while 1:
以迭代1
开始,索引方法进行线性搜索,并在第一个匹配项停止。如果找不到匹配项,则会引发ValueError
异常。
list = ['dog','cat','pizza','trump', 'computer', 'trump']
value = "trump"
i = -1
try:
while 1: # Start with Iteration 1 never 0
i = list.index(value, i+1)
print(value,"at", i)
except ValueError: # No matching item is found.
pass
trump at 3
trump at 5