亲宝软件园·资讯

展开

python对常见数据类型的遍历解析

人气:0

字符串遍历

>>> a_str = "hello itcast"
>>> for char in a_str:
...   print(char,end=' ')
...
h e l l o  i t c a s t

列表遍历

>>> a_list = [1, 2, 3, 4, 5]
>>> for num in a_list:
...   print(num,end=' ')
...
1 2 3 4 5

元组遍历

>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
...   print(num,end=" ")
1 2 3 4 5

字典遍历

遍历字典的key(键)

>>> a_dict = {"name":"lxy","sex":"男","age":18}
>>> for key in a_dict.keys():
  print(key)  
name
sex
age

遍历字典的value(值)

>>> a_dict = {"name":"lxy","sex":"男","age":18}
>>> for value in a_dict.values():
  print(value)
lxy
男
18
>>> 

遍历字典的项(元素)

>>> a_dict = {"name":"lxy","sex":"男","age":18}
>>> for key,value in a_dict.items():
  print("key=%s,value=%s"%(key,value))  
key=name,value=lxy
key=sex,value=男
key=age,value=18

重点:带下标索引的遍历

正常情况我们是这样的

>>> chars = ['a', 'b', 'c', 'd']
>>> i = 0
>>> for chr in chars:
...   print("%d %s"%(i, chr))
...   i += 1
...
0 a
1 b
2 c
3 d

升级版使用enumerate()

>>> chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
  print(i,chr) 
0 a
1 b
2 c
3 d
>>> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论