我将检查列表中是否存在单词。 我怎样才能显示这个词的位置?
答案 0 :(得分:27)
list = ["word1", "word2", "word3"]
try:
print list.index("word1")
except ValueError:
print "word1 not in list."
这段代码将打印0
,因为这是第一次出现"word1"
答案 1 :(得分:3)
要检查 对象是否在列表中,请使用in
运算符:
>>> words = ['a', 'list', 'of', 'words']
>>> 'of' in words
True
>>> 'eggs' in words
False
使用列表的index
方法查找列表中的 where ,但要准备好处理异常:
>>> words.index('of')
2
>>> words.index('eggs')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'eggs' is not in list
答案 2 :(得分:2)
您可以使用['hello', 'world'].index('world')
答案 3 :(得分:2)
以下代码:
sentence=["I","am","a","boy","i","am","a","girl"]
word="am"
if word in sentence:
print( word, " is in the sentence")
for i, j in enumerate(sentence):
if j == word:
print("'"+word+"'","is in position",i+1)
会产生这个输出:
"am" is in position 1
"am" is in position 5
这是因为在python中索引从0开始
希望这有帮助!
答案 4 :(得分:1)
使用枚举-查找列表中所有给定字符串的出现
listEx=['the','tiger','the','rabit','the','the']
print([index for index,ele in enumerate(listEx) if ele=='the'])
输出
[0, 2, 4, 5]
答案 5 :(得分:0)
听起来你想要indexof。来自here:
operator.indexOf(a,b)¶ 返回a中出现第一个b的索引。
答案 6 :(得分:0)
假设该单词的名称为“Monday”:
您需要一个列表作为初始数据库:
myList = ["Monday", "Tuesday", "Monday", "Wednesday", "Thursday", "Friday"]
然后你需要使用for,next(),iter()和len()函数逐个循环遍历列表:
myIter = iter(myList)
for i in range(0, len(myList)):
next_item = next(myIter)
现在在循环时,你需要检查想要的单词是否存在以及它存在于何处,打印出来:
if next_item == "Monday":
print(i)
共:
myList = ["Monday", "Tuesday", "Monday", "Wednesday", "Thursday", "Friday"]
myIter = iter(myList)
for i in range(0, len(myList)):
next_item = next(myIter)
if next_item == "Monday":
print(i)
由于此列表中有两个星期一,因此此示例的结果将是: 0 2