开发者

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

开发者 https://www.devze.com 2022-12-11 17:52 出处:网络
for s in stocks_list: 开发者_如何学Pythonprint 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 us
for s in stocks_list:
 开发者_如何学Python   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']


The position is called by stocks_list.index(s), for example:

for s in stocks_list:
    print(stocks_list.index(s))
0

精彩评论

暂无评论...
验证码 换一张
取 消