简体   繁体   中英

How to find the position of an element in a list , in Python?

for s in stocks_list:
    print s

how do I know what "position" s is in? So that I can do stocks_list[4] in the future?

If you know what you're looking for ahead of time you can use the index method:

>>> stocks_list = ['AAPL', 'MSFT', 'GOOG']
>>> stocks_list.index('MSFT')
1
>>> stocks_list.index('GOOG')
2
for index, s in enumerate(stocks_list):
    print index, s
[x for x in range(len(stocks_list)) if stocks_list[x]=='MSFT']

该位置由stocks_list.index(s) 调用,例如:

    print (stocks_list.index(s))

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