简体   繁体   中英

Using a for loop to find the location of all strings in a list (Python 2.7)

I am currently trying to create a list of string locations from a list of strings. I tried to search this, but most of the tutorials only seemed to cover printing using for loops.

message = "Example string."
L = ['m', 'p', 'l']
for P in range(len(L)):
    message.find(L)

This is a mockup code that doesn't work, but this is an example of the string:

INPUT :

message = "Example string."
L = ['m', 'p', 'l']

I want to define a new list that will return

[3, 4, 5]

Using simple list comprehension :

>>> out = [ message.find(s) for s in L]
>>> out
=> [3, 4, 5]

#driver values :

IN : message = "Example string."
IN : L = ['m', 'p', 'l']

list comp是一个更好的解决方案:

[message.index(c) for c in L]

Try this

>>> L = ['m', 'p', 'l']
>>> lst=[]
>>> for i in L:
        lst.append(message.index(i))

>>> lst
[3, 4, 5]

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