One minute
Python遍历
python遍历集合
-
遍历数组:
for item in [1,3,4,8,"hello"]: print(item,end=" ")
-
遍历字符串:
for c in 'PYTHON123': print(c,end=" ")#每个字符后面有一个空格
-
遍历字典:
student = {'num': '123456', 'name': 'kelvin', 'age': 18} for key, value in student.items(): print("\nKey: " + key) print("Value: " + str(value)) # 因为age对应的是数字类型,所以用str()方法将其转化成字符串 for item in dict.items(): print(item) for key in student: print(key) for value in student.values(): print(value)
-
遍历对象:
for attr in dir(obj): print(attr) obj.__dict__
-
遍历元组:
mytuple = (1,2,3,4,5) for t in mytuple: print(t)
-
遍历扩展:
for s in "BAT": print("循环进行中:"+s) else: print("循环正常结束")
-
遍历文件:
for line in fi:
-
升级版使用
enumerate()
- 介绍:enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
- 语法:enumerate(sequence, [start=0])
- 参数:
- sequence – 一个序列、迭代器或其他支持迭代对象。
- start – 下标起始位置。
- 返回值:返回 tuple(元组) 对象。
chars = ['a', 'b', 'c', 'd']
for i, chr in enumerate(chars):
print(i,chr)
Read other posts