开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜