[英]How to find index of second occurrence of a phrase in a string in Python 3?
[英]Find the index of the second occurrence of a string inside a list
這是我的清單和代碼:
x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
for line in x:
y=x.index(line)
#code
第一次獲得“ this”,它可以正常工作,但是第二次,它僅獲得第一個“ this”的索引!
如何在列表中找到第二次出現的字符串?
您可以使用列表切片輕松地獲得秒。 在下面的示例中,我們找到第一次出現的索引,然后在剛出現第一次的子列表中找到第一次出現的索引。
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
切記,如果對象不在列表中,則使用list.index()
將返回ValueError
。 因此,您可能希望圍繞內部循環進行一些異常處理。
因此,最終代碼看起來將更接近於此:
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
您可以在此處使用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']
如果只需要獲取關鍵字的索引,那么就不需要在列表中存儲字符串(即使這只是您想到的一個示例!)。
此函數將打印出每一行以及您在文件中每行找到的關鍵字的所有索引(如果有):
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”和第1/2次出現。 例如,假設您的文件如下所示:
hello this
this is cool
hello there
this this 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.