Home >Backend Development >Python Tutorial >Python methods to traverse serial numbers and values ​​in a list (three methods)

Python methods to traverse serial numbers and values ​​in a list (three methods)

高洛峰
高洛峰Original
2017-02-20 10:08:451695browse

Three ways to traverse the serial numbers and values ​​in the list:

I recently learned the language python and felt that it has greatly improved my work efficiency, so I wrote this on Valentine's Day. In this blog, without further ado, I will post the code directly

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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))
 # 方法3
 print '\n遍历列表方法3 (设置遍历开始初始位置,只改变了起始序号):'
 for i, val in enumerate(list, 2):
 print ("序号:%s 值:%s" % (i + 1, val))

The result after running the code is as shown below:

Python 遍历列表里面序号和值的方法(三种)

Here is an introduction to the enumerate() method, which can be viewed by viewing the help() function. The query results are as follows:

Python 遍历列表里面序号和值的方法(三种)

Finally, a reminder, enumerate( )The second parameter of the function only changes the starting value of the serial number, and does not change other things

For more Python methods to traverse the serial numbers and values ​​​​in the list (three methods), please pay attention to PHP Chinese for related articles net!

Statement:
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