How to traverse a list in python

爱喝马黛茶的安东尼
Release: 2019-07-10 13:47:07
Original
4325 people have browsed it

How to traverse a list in python

How does Python traverse the list to perform operations? Here are three methods:

if __name__ == '__main__':  
list = ['html', 'js', 'css', 'python']  
# 方法1 
print '遍历列表方法1:' 
    for i in list:  
       print ("序号:%s 值:%s" % (list.index(i) + 1, i)) 

print '\n遍历列表方法2:'
# 方法2
    for i in range(len(list)): 
       print ("序号:%s 值:%s" % (i + 1, list[i])) 
 
# 方法3
print '\n遍历列表方法3:'
    for i, val in enumerate(list): 
       print ("序号:%s 值:%s" % (i + 1, val)) 
 
print '\n遍历列表方法3 (设置遍历开始初始位置,只改变了起始序号):'
    for i, val in enumerate(list, 2): 
       print ("序号:%s 值:%s" % (i + 1, val))
Copy after login

The result after running the code is as shown below:

How to traverse a list in python

The above is the detailed content of How to traverse a list in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!