简体   繁体   中英

How does this line of code work? (Python, function)

def superindex(string, word):
    return [i for i, ltr in enumerate(string) if ltr == word]

I'm a beginner with Python and I would like to know how this look works.

  1. How does it create a list?
  2. What does i for i do?

It returns the indices where the letter word matches a character in the string variable.

for i, ltr in enumerate(string) is a for loop over the letters in string , because you're using enumerate you also get an index i as well. However adding the if condition on the end means you only return i when the letter ltr equals the letter word

So this

string = "yuppers"
word = "p"
print(superindex(string, word))

will return this

[2,3]

Would be much easier for you to under stand if it was written like this :

lst = []
for i, ltr in enumerate(string):
    if (ltr == word):
        lst.append(i)

The easy way to understand single-line for loop is using more basic things:

>>> l = ["a", "b", "c"]
>>> [ltr for ltr in l]
['a', 'b', 'c']

For your first question, using square brackets creates a list and it appends the ltr value to the list by iterating over the list l .

The enumerate is a built-in function which allows having a counter while looping over an iterable object. Here, i iterates over indexes of the list while ltr iterates over the elements of the list l . Here is another example:

>>> [i for i, ltr in  enumerate(l)]
[0, 1, 2]
>>> [ltr for i, ltr in  enumerate(l)]
['a', 'b', 'c']

Additioanlly, you have a condition at the end:

>>>[ltr for i, ltr in  enumerate(l) if i>0]
['b', 'c']

Here, it only takes the elements of the list l with indexes greater than 0 .

I hope, this helps understanding the concepts :)

This function is creating a list of the ltr indexes of an iterable variable string , that match the object word

This function can be written in a simpler way:

    def superindex(string, word):
        l = list()
        for i, ltr in enumerate(string):
            if ltr == word: # check if ltr is equal to the variable word
                l.append(i) # append the index i of the matching ltr in the string
        return l

enumerate

  • The enumerate function allows us to loop over something and have an automatic counter
  • Here each 'ltr' in the variable 'string' is assigned a number 'i' (starting from zero)

[i for i...

This function will work on letters:
superindex('foo', 'o')
returns [1,2]

and also lists of words:
superindex(['foo', 'bar'], 'bar')
returns [1]

Note: Although the variables suggest this is applicable to string and words, a more appropriate naming might be ( list_of_strings and word ) or ( string and letter ). If a more general case was sought maybe ( iterable and template )...

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