[英]Find the index of the second occurrence of a string inside a list
This is my list and code: 这是我的清单和代码:
x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
for line in x:
y=x.index(line)
#code
The first time it gets "this", it works properly, but for the second time, it gets the index of the first "this" only! 第一次获得“ this”,它可以正常工作,但是第二次,它仅获得第一个“ this”的索引!
How can I find the second occurrence of a string inside a list? 如何在列表中找到第二次出现的字符串?
You can get the second easily enough by using list slices . 您可以使用列表切片轻松地获得秒。 In the example below, we find the index of the first occurance and then find the index of the first occurance in the sub-list that begins just after the first occurance.
在下面的示例中,我们找到第一次出现的索引,然后在刚出现第一次的子列表中找到第一次出现的索引。
x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
for line in x:
first=x.index(line)
second=x[first+1:].index(line)
#code
Bare in mind that using list.index()
will return a ValueError
if the object isn't in the list. 切记,如果对象不在列表中,则使用
list.index()
将返回ValueError
。 Thus you may want some exception handling around your inner loop. 因此,您可能希望围绕内部循环进行一些异常处理。
So the final code will look somewhat closer to this: 因此,最终代码看起来将更接近于此:
x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
for line in x:
print lines
try:
first=x.index(line)
second=x[first+1:].index(line)
except:
first,second=-1,-1
print first,second
#code
You could use enumerate(...)
here. 您可以在此处使用
enumerate(...)
。
>>> x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
>>> for index, line in enumerate(x):
print index, line
0 ['hi hello']
1 ['this is other']
2 ['this']
3 ['something']
4 ['this']
5 ['last element']
If getting the indices of the keyword is the only thing you need to do, then storing strings in a list is unnecessary (even if this was just an example you thought of!). 如果只需要获取关键字的索引,那么就不需要在列表中存储字符串(即使这只是您想到的一个示例!)。
This function would print out each line and all the indices of the keyword (if any) that you give found per line in the file: 此函数将打印出每一行以及您在文件中每行找到的关键字的所有索引(如果有):
def getIndices(keyword):
f = open('pathToYourFile', 'r')
for line in f:
wordList = line.split()
buf = line.strip("\n") + ": "
i = 0
while i < len(wordList):
if wordList[i] == keyword:
buf += str(i) + " "
i += 1
print buf
This way you won't be limited to the keyword "this" and 1st/2nd occurrences. 这样,您将不仅限于关键字“ this”和第1/2次出现。 For example, let's say your file looked like this:
例如,假设您的文件如下所示:
hello this
this is cool
hello there
this this this
Then the function will work like this: 然后该函数将像这样工作:
>>> getIndices("this")
hello this: 1
this is cool: 0
hello there:
this this this: 0 1 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.