2024-10-05 14:32:01 发布
网友
我尝试使用python来查找下面文本中单词“the”的索引
sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.']
如果我做sent3.index('the'),我得到1,这是该词第一次出现的索引。我不确定的是如何找到“the”出现的其他时间的索引。有人知道我该怎么做吗?在
sent3.index('the')
1
谢谢!在
[i for i, item in enumerate(sent3) if item == wanted_item]
演示:
^{}只是从iterable构造一个元组的list,由它们的值和相应的索引组成。我们可以用这个来检查这个值是否是我们想要的,如果是的话,从中提取索引。在
list
>>> from collections import defaultdict >>> sent3 = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.'] >>> idx = defaultdict(list) >>> for i,j in enumerate(sent3): ... idx[j].append(i) ... >>> idx['the'] [1, 5, 8]
演示:
^{pr2}$^{} 只是从iterable构造一个元组的
list
,由它们的值和相应的索引组成。我们可以用这个来检查这个值是否是我们想要的,如果是的话,从中提取索引。在相关问题 更多 >
编程相关推荐