[英]IndexError: string index out of range - How do I get this error when the index does not go outside the range of called list?
[英]How do I pull the string before and after a specific string in a list without going out of index range?
假設我有以下列表:
x = ['i like cats', 'i like dogs', 'i like both']
我想在其中找到帶有“ dogs”一詞的字符串,然后將字符串前后連接起來以形成序列“我喜歡貓。我喜歡狗。我都喜歡”。 我做到以下幾點:
for position in range(len(x)):
if 'dogs' in x[position]:
print x[position - 1] + ". " + x[position] + ". " + x[position + 1] + "."
例如,當我在列表的末尾查找字符串時遇到問題:
for position in range(len(x)):
if 'both' in x[position]:
print x[position - 1] + ". " + x[position] + ". " + x[position + 1] + "."
當我這樣做時,出現以下錯誤:
IndexError: list index out of range
這樣做的最佳方法是什么,以便如果字符串位於列表的最末端,則它會忽略其后的索引,以便在提供的示例中將其打印出“我喜歡狗。我都喜歡”? 此外,如果我要在其中查找帶有“ cats”一詞的字符串,例如:
for position in range(len(x)):
if 'cats' in x[position]:
print x[position - 1] + ". " + x[position] + ". " + x[position + 1] + "."
它打印出“我都喜歡。我喜歡貓。我喜歡狗”。 我希望它打印出“我喜歡貓。我喜歡狗”。
我正在從網站中提取大量文本並將單個字符串轉儲到列表中,以便可以找到語言模式並將其寫入文件,因此我需要能夠忽略列表的開頭和結尾。
檢查位置是否等於len(x)。 如果是這樣
print x[position - 1] + ". " + x[position] + "."
否則以正常方式打印。
請嘗試以下解決方案。 它適用於所有情況。
x = ['i like cats', 'i like dogs', 'i like both']
for position in range(len(x)):
if 'cats' in x[position]:
print ".".join([x[pos] for pos in range(position-1, position+2) if pos in range(0, len(x))]) + "."
使用列表切片。 如果數組索引超出范圍,它將在最后自動截斷。
x = ['i like cats', 'i like dogs', 'i like both']
for position in range(len(x)):
if 'both' in x[position]:
print ('.'.join([ele for ele in x[0:2]]) if position==0 else '.'.join([ele for ele in x[position-1:position+2]]))
def combine(items, target):
result = []
for index, value in enumerate(items):
if target in value:
result.append('. '.join(items[0:2]) if index == 0 else '. '.join(items[index-1:index+2]))
return result
使用列表slice
獲取目標的上一個和下一個項目。 如果索引大於長度,python只會忽略它,而不會引發錯誤。 使用enumerate
迭代list
。
嘗試這個:
>>> x = ['i like python', 'i like cats', 'i like dogs', 'i like both']
>>> def concat(term, x):
... for a in x:
... i = x.index(a)
... if term in a and i+1 < len(x):
... return '. '.join([ x[i-1], a, x[i+1] ])
... elif term in a:
... return '. '.join([ x[i-1], a ])
>>> # check
>>> concat('dogs', x)
'i like cats. i like dogs. i like both'
>>> concat('both', x)
'i like dogs. i like both'
另一種選擇( try except
)
>>> def concat(term, x):
... for a in x:
... if term in a:
... i = x.index(a)
... try:
... return '. '.join([x[i-1], a, x[i+1]])
... except IndexError:
... return '. '.join([x[i-1], a])
>>> # check
>>> concat('dogs', x)
'i like cats. i like dogs. i like both'
>>> concat('both', x)
'i like dogs. i like both'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.