Python 在列表中的位置?

Python 在列表中的位置?,python,list,position,Python,List,Position,我将检查列表中是否存在单词。 如何显示这个词的位置 list = ["word1", "word2", "word3"] try: print list.index("word1") except ValueError: print "word1 not in list." 这段代码将打印0,因为这是第一次出现的“word1”的索引,听起来像是要索引。发件人: 运算符.indexOf(a,b)“” 返回a中第一次出现b的索引 您可以使用['hello','world'].索引('w

我将检查列表中是否存在单词。 如何显示这个词的位置

list = ["word1", "word2", "word3"]
try:
   print list.index("word1")
except ValueError:
   print "word1 not in list."

这段代码将打印
0
,因为这是第一次出现的
“word1”

的索引,听起来像是要索引。发件人:

运算符.indexOf(a,b)“” 返回a中第一次出现b的索引


您可以使用
['hello','world'].索引('world')
要检查对象是否在列表中,请使用
中的
操作符:

>>> 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
单词索引('of') 2. >>>单词索引(‘鸡蛋’) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 ValueError:“鸡蛋”不在列表中
以下代码:

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开始


希望这有帮助

假设单词的名称为“星期一”:

您需要一个列表作为初始数据库:

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

使用枚举-查找列表中给定字符串的所有出现项

listEx=['the','tiger','the','rabit','the','the']
print([index for index,ele in enumerate(listEx) if ele=='the'])
输出

[0, 2, 4, 5]

就我个人而言,我认为如果你希望单词出现在数组中,那么异常方法是有效的,但也许那只是我。否则,您可以在找到索引之前测试列表中是否存在该单词,如jleedev所示。@leeman他要求提供一个函数,该函数将返回列表中某个值的索引,我将该函数与所有用例一起提供给了他。我同意jleedev的解决方案更舒适,但我尝试为
.index
IMHO提供所有用例。在
中使用
.index()
,try/except
是最有效的方法,因为它只搜索一次匹配项,并且在使用[EAFP]的意义上完全是“Pythonic”(Pythonic)(请求原谅比允许更容易)编程风格。@Lee Man:忽略双重查找,如果很少出现异常情况,那么使用异常的代码将比其他代码具有更好的平均性能。您可以通过搜索已提出此问题的人员并阅读此处已给出的答案来完成此操作。或者将回答您的问题。可能重复