简体   繁体   中英

In python what does [pos for pos, word in enumerate(sentence, start=1) if word == word_positions] actually do in my code?

I know this question comes off as a bit, silly, I mean, I wrote the code! This particular bit of code however I got off a website I can no longer find, and I need to do a write up on the code.

Here's the code:

sentence = input("Please input a sentence\n").lower().split() 
# Assigns a sentence to a variable, puts it into lower case and then splits the string into words

word_positions = input("Please input a word\n") 
# Assigns a word for the program to print its positions 

end = [pos for pos, word in enumerate(sentence, start=1) if word == word_positions]

print (end)
# prints the positions of the word

The results of running the code look like:

Please input a sentence
The cat sat on the mat
Please input a word
the
[1, 5]

Its just [pos for pos, word in enumerate(sentence, start =1) if word == word positions] that I need to know what it does.

end = [pos for pos, word in enumerate(sentence, start=1) if word == word_positions]

enumerate will create an iterable enumerate object of tuples. I have used list(...) to make it clear

>>> list(enumerate(['a','b','c'], start=1))
[(1, 'a'), (2, 'b'), (3, 'c')]

so pos for pos,word in ... if condition

means "given the tuple (pos,word) " give me the first element (ie pos) if the condition is met. In this case the condition is that the second element of the tuple (pos,word) must be equal to word_positions

As this is a list comprehention this will be carried out for every tuple in the enumerate object (ie the pairs of number,word)

Note that pos for (pos,word) in ... if condition is the same and a bit clearer.

It's the same as

end = []
i = 0
while i < len(sentence):
    if sentence[i] == word_positions:
        end.append(i+1)
    i += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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