zoukankan      html  css  js  c++  java
  • python中的几种遍历列表的方法比较 C

    python的内容非常丰富,给我们带来的便利很多,很多事情的表达方法有很大的多样性,比如我经常需要遍历一个列表,取它的下标和值,这个时候就有很多方法需要取舍一下才行。

    for循环遍历
    	l = [1,2,3,4,5,6,7]
    	for i in range(len(l)):
    		print i,  l[i]
    		
    	非常简单,没有学过python的人也可以大致看懂
    
    while循环遍历
    l = [1,2,3,4,5,6,7,8]
    index = 0
    while index < len(l):
    	print index, l[index]
    	index++
    	
    很有c语言背景的写法,java的也类似的说
    
    index结合for循环遍历
    l = [1,2,3,4,5,6,7]
    index = 0
    for i in l:
    	print index,  i
    	index += 1
    
    拉链(zip)方法遍历
    l = [1,2,,4,5,6,6]
    for i ,v in zip(range(len(l)), l):
    	print i, v
    	
    看起来好复杂的说,zip把它的2个参数组合成了list长度的元组列表,其实每个元组的值是2个列表中的每一个,所以它叫做拉链方法
    

    enumerate遍历方法

    l = [1,2,3,4,4,4,4]
    for i, v in enumerate(l):
    	print i , v
    	
    非常容易理解而是是懒加载的方法,其中用到了python中的生成器,我们也可以实现自己的enumerate方法,用同样的for循环方式进行调用
    
    比如说
    
    def	my_enumerate(l):
    	length= len(l)
    	for i in range(length):
    		yield i , l[i]
    		
    调用方法和上面完全一样,你也可以写一个自动生成斐波那契的函数,比如这样写就可以自动获取前n项斐波那契数列
    def fib(max):
    	index = 0 
    	a, b = 0, 1
    	while index < max:
    		yield index, a
    		a, b= b, a+b
    		index +=1
    		
    for i , v in fib(10):
    	print i , b
    	
    这样调用非常方便,易读而且有懒加载的功能,其实就相当于开启一个协程。
  • 相关阅读:
    CNN comprehension
    Gradient Descent
    Various Optimization Algorithms For Training Neural Network
    gerrit workflow
    jenkins job配置脚本化
    Jenkins pipeline jobs隐式传参
    make words counter for image with the help of paddlehub model
    make words counter for image with the help of paddlehub model
    git push and gerrit code review
    image similarity
  • 原文地址:https://www.cnblogs.com/youngershen/p/3973997.html
Copyright © 2011-2022 走看看