简体   繁体   English

从列表中找到单词的 position

[英]Locating the position of a word from a list

Hi I'm doing an assignment for school and part of it involves displaying the position of a word in a sentence and I searched it up and found this:嗨,我正在为学校做作业,其中一部分涉及在句子中显示单词的 position,我搜索了一下,发现了这个:

for i in [i for i,x in enumerate(list, start=1) if x == word]:
     print (i)

However I don't understand how this works so could someone please break it up and explain it to me但是我不明白这是如何工作的所以有人可以把它分解并向我解释

If it helps this is the rest of my code for this part of the assignment:如果有帮助,这是我的这部分作业代码的 rest:

list = ["apple", "banana", "carrot","pear"]
print (list)
word = input("Enter a word from this list: ")
for i in [i for i,x in enumerate(list, start=1) if x == word]:
      print (i)

Awkwardness尴尬

First, you should not use list as a variable because list is one of the default Python functions.首先,您不应将list用作变量,因为list是默认的 Python 函数之一。 If you do so, the list() function (which is also a type) is replace by your variable in the local scope. So I renamed it alist .如果这样做, list() function(也是一种类型)将替换为本地 scope 中的变量。所以我将其重命名为alist

alist = ["apple", "banana", "carrot", "pear"]

Explanation解释

The following statement is a comprehension list:以下语句是一个理解列表:

result = [i for i, x in enumerate(alist, start=1) if x == word]

This comprehension list can be written like this:这个理解列表可以这样写:

result = []
for i, x in enumerate(alist, start=1):
    if x == word:
        result.append(i)

For instance:例如:

>>> alist = ["apple", "banana", "carrot", "pear"]
>>> word = "carrot"
>>> [i for i, x in enumerate(alist, start=1) if x == word]
[3]

This comprehension list returns all the positions of the word "carrot" in ["apple", "banana", "carrot", "pear"].这个理解列表返回单词“carrot”在[“apple”、“banana”、“carrot”、“pear”]中的所有位置。

The loop:循环:

for i in [i for i, x in enumerate(alist, start=1) if x == word]:
    print(i)

Is vainly complex because it iterates the comprehension list.徒劳地复杂,因为它迭代了理解列表。

You can simplify like this:你可以这样简化:

print([i for i, x in enumerate(alist, start=1) if x == word])

Or:或者:

for i, x in enumerate(alist, start=1):
    if x == word:
        print(i)

Note: alist.index(word) + 1 can give the first word position in the list.注意: alist.index(word) + 1可以给出列表中的第一个单词 position。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM