您可以在tokens 列表中使用index() 这样做:
punc = ['.', '!', '?']
tokens = ['today', 'i', 'went', 'to', 'the', 'park', '.', 'it', 'was', 'great', '!']
for p in punc:
if p in tokens:
print(p, tokens.index(p), sep=" index is: ")
else:
print(p, 'not found', sep=' ')
此代码将打印标记中的所有 punc 索引(如果存在)。
使用列表理解:
[print(p, tokens.index(p), sep=" index is: ") if p in tokens else print(p, 'not found', sep=' ') for p in punc]
输出:
. index is: 6
! index is: 10
? not found
如果您只想检查第一项而不是整个punc 列表:
print(tokens.index(punc[0]) if punc[0] in tokens else 'not found')
输出:
6
使用[index()]可以在元素不在列表中时产生ValueError异常:
Exception has occurred: ValueError
'?' is not in list
在您的情况下,? 中不存在 tokens 的值可能会发生这种情况。
要解决这个问题,您有两种简单的方法:
- 检查该项目是否在列表中,例如:
'?' in tokens(这是干净/可红色的方法)
- 将
.index() 调用封装在try/except 中并对其进行管理。 (这是快速的方法)