美文网首页
python遍历

python遍历

作者: lfpwhy | 来源:发表于2018-01-09 07:32 被阅读0次
# -*- coding:utf-8 -*-
# or...in...:遍历字符串、列表、元组、字典等数据结构。
# 字符串遍历
mystr="hello python"
for  py in mystr:
    print(py,end="")
print(" ")
# 列表遍历
mylist=[1,2,3,4,5,6]
for num in mylist:
    print(num,end=" ")
print(" ")
# 元组遍历
mytuple=(8,9,10,11,12,13,)
for num1 in mytuple:
    print(num1,end=" ")
print(" ")
# 字典遍历
mydict={'姓名':'李四','性别':'男','身高':180}
# 遍历键
for key in mydict.keys():
    print(key,end=" ")
print(" ")
#遍历值
for value in mydict.values():
    print(value,end="  ")
print(" ")
#遍历所有元素
for item in mydict.items():
    print(item,end="  ")
print(" ")
# 遍历键值对
for key,value  in mydict.items():
    print("key=%s,value=%s"%(key,value))
print(" ")
# 下标索引遍历,enumerate用于在for循环中得到计数
chars=['a','b','c','d']
for  i,chr in enumerate(chars):
    print(i,chr,end=' ')

相关文章

网友评论

      本文标题:python遍历

      本文链接:https://www.haomeiwen.com/subject/xotwnxtx.html