列表中的位置?
我想检查一个单词是否在一个列表里。
我该怎么做才能显示这个单词的位置呢?
7 个回答
2
你可以使用 ['hello', 'world'].index('world')
这个代码。
3
要检查一个对象是否在列表中,可以使用 in
操作符:
>>> words = ['a', 'list', 'of', 'words']
>>> 'of' in words
True
>>> 'eggs' in words
False
如果想知道这个对象在列表中的位置,可以使用列表的 index
方法,但要准备好处理可能出现的错误:
>>> words.index('of')
2
>>> words.index('eggs')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'eggs' is not in list
29
list = ["word1", "word2", "word3"]
try:
print list.index("word1")
except ValueError:
print "word1 not in list."
这段代码会输出 0
,因为 "word1"
第一次出现的位置是第0个索引。