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
#-×-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) #方法2 print'遍历列表方法2' for i in range(len(list)): print '序号:{}的值为{}'.format(i+1,list[i]) #方法3 print
list = ['html', 'js', 'css', 'python'] 遍历列表方法1:for i in list: print("序号:%s 值:%s" % (list.index(i) + 1, i)) 遍历列表方法2:for i in range(len(list)): print("序号:%s 值:%s" % (i + 1, list[i])) 遍历列表方法3:for i, val in enumerate(list): print("序号:
在Python中有六种内建的序列:列表.元组.字符串.Unicode字符串.buffer对象和xrange对象.在这里暂时只讨论字符串.列表和元组的遍历. 一. 序列遍历 序列有两种遍历:一种通过值 另外一种通过索引 1.1 值遍历:s='abc'for x in s: print x z=('andy','leaf')for x in z: print x z={'tree','leaf'}for x in z: print x 1.2 索引遍历: l='abcd'for x in range
先放一个python遍历发生的异常: ls =[1,2,3,4,5,6,7,8,9] for i in ls: print("i",i) print("ls",ls) ls.remove(i) 运行结果: i 1 ls [1, 2, 3, 4, 5, 6, 7, 8, 9] i 3 ls [2, 3, 4, 5, 6, 7, 8, 9] i 5 ls [2, 4, 5, 6, 7, 8, 9] i 7 ls [2, 4, 6, 7, 8, 9] i 9 ls [2,
当前文件夹下,把所有文件名中的"50076"替换成"50092",用Python实现,代码所下: # encoding: utf-8 import os import os.path curDir = os.getcwd() oldId = "50076" newId = "50092" for parent, dirnames, filenames in os.walk(curDir): for filename in fi
前置知识 for 循环详解:https://www.cnblogs.com/poloyy/p/15087053.html 使用 for key in dict 遍历字典 可以使用 for key in dict 遍历字典中所有的键 x = {'a': 'A', 'b': 'B'} for key in x: print(key) # 输出结果 a b 使用 for key in dict.keys () 遍历字典的键 字典提供了 keys () 方法返回字典中所有的键 # keys book =
#遍历字典, 分别打印key, value, key:value emp = {'name':'Tom', 'age':20, 'salary' : 8800.00} for k in emp.keys(): print('key = {}'.format(k)) for v in emp.values(): print('values = {}'.format(v)) for v,k in emp.items(): print('{v}:{k}'.format(v = v, k = k)) 打