如何在Python列表中查找元素的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4097338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:14:33  来源:igfitidea点击:

How to find index of an element in Python list?

pythonlistindexing

提问by Gusto

Possible Duplicate:
How to find positions of the list maximum?

可能的重复:
如何找到列表最大值的位置?

A question from homework: De?ne a function censor(words,nasty)that takes a list of words, and replaces all the words appearing in nasty with the word CENSORED, and returns the censored list of words.

作业中的一个问题:定义一个函数censor(words,nasty),该函数接受一个单词列表,并用 CENSORED 替换所有出现在 nasty 中的单词,并返回经过的单词列表。

>>> censor(['it','is','raining'], ['raining'])
['it','is','CENSORED']

I see solution like this:

我看到这样的解决方案:

  1. find an index of nasty
  2. replace words matching that index with "CENSORED"
  1. 找到一个索引 nasty
  2. 替换与该索引匹配的单词 "CENSORED"

but i get stuck on finding the index..

但我被困在寻找索引..

采纳答案by z4y4ts

Actually you don't have to operate with indexes here. Just iterate over wordslist and check if the word is listed in nasty. If it is append 'CENSORED'to the result list, else append the word itself.

实际上,您不必在这里操作索引。只需遍历words列表并检查单词是否在nasty. 如果它附加'CENSORED'到结果列表,否则附加单词本身。

Or you can involve list comprehensionand conditional expressionto get more elegant version:

或者你可以使用列表理解条件表达式来获得更优雅的版本:

回答by MAK

You can find the index of any element of a listby using the .indexmethod.

您可以list使用.index方法找到 a 的任何元素的索引。

>>> l=['a','b','c']
>>> l.index('b')
1

回答by Konrad Rudolph

Your approach might work, but it's unnecessarily complicated.

您的方法可能有效,但它不必要地复杂。

Python allows a very simple syntax to check whether something is contained in a list:

Python 允许使用非常简单的语法来检查列表中是否包含某些内容:

censor = [ 'bugger', 'nickle' ]
word = 'bugger'
if word in censor: print 'CENSORED'

With that approach, simply walk over your list of words and test for each words whether it's in the censorlist.

使用这种方法,只需遍历您的单词列表并测试每个单词是否在censor列表中。

To walk over your list of words, you can use the forloop. Since you might need to modify the current word, use an index, like so:

要遍历您的单词列表,您可以使用for循环。由于您可能需要修改当前单词,请使用索引,如下所示:

for index in len(words)):
   print index, words[index]

Now all you need to do is put the two code fragments together.

现在您需要做的就是将两个代码片段放在一起。

回答by martineau

You could use the handy built-in enumerate()function to step through the items in the list. For example:

您可以使用方便的内置enumerate()函数来逐步浏览列表中的项目。例如:

def censor(words, nasty):
    for i,word in enumerate(words):
       if word...