python对常见数据类型的遍历解析
作者:三国小梦 时间:2022-01-18 21:24:28
字符串遍历
>>> 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()
介绍:enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法:enumerate(sequence, [start=0])
参数:
sequence -- 一个序列、迭代器或其他支持迭代对象。
start -- 下标起始位置。
返回值:返回 tuple(元组) 对象。
>>> chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
print(i,chr)
0 a
1 b
2 c
3 d
>>>
来源:https://www.cnblogs.com/lxy0/p/11337019.html
标签:python,数据,类型,遍历
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python GAE、Django导出Excel的方法
2023-02-27 13:59:09
Python的函数使用介绍
2022-07-02 12:05:42
![](https://img.aspxhome.com/file/2023/2/93612_0s.png)
Python中如何优雅的合并两个字典(dict)方法示例
2023-08-02 16:15:25
使用keras实现densenet和Xception的模型融合
2022-04-15 19:17:01
![](https://img.aspxhome.com/file/2023/1/77901_0s.jpg)
tensorflow 1.0用CNN进行图像分类
2022-08-17 17:32:29
asp如何让浏览器在https和http之间转化?
2010-05-13 16:37:00
ORACLE 报警日志如何查看?第1/2页
2009-07-02 12:06:00
用Python制作检测Linux运行信息的工具的教程
2022-03-01 17:49:15
数据库分页大全(mssql,mysql,oracle)
2010-10-25 20:02:00
Python json转字典字符方法实例解析
2021-06-07 11:21:40
有啊在设计上相对淘宝的优势
2009-05-22 12:28:00
用FrongPage设计网页花样
2008-09-17 10:47:00
Python实现从多表格中随机抽取数据
2022-07-01 01:58:18
![](https://img.aspxhome.com/file/2023/1/83931_0s.png)
Python测试框架pytest介绍
2023-08-03 01:47:59
![](https://img.aspxhome.com/file/2023/7/92007_0s.png)
Python Pyecharts绘制桑基图分析用户行为路径
2022-06-07 02:47:57
![](https://img.aspxhome.com/file/2023/7/79527_0s.jpg)
Pytorch深度学习addmm()和addmm_()函数用法解析
2021-01-02 04:04:25
![](https://img.aspxhome.com/file/2023/2/95252_0s.gif)
使用TensorFlow实现简单线性回归模型
2022-11-30 19:51:48
![](https://img.aspxhome.com/file/2023/5/92515_0s.jpg)
浅谈golang for 循环中使用协程的问题
2023-08-28 11:26:59
asp如何实现网络打印?
2010-05-24 18:31:00
用Python实现给Word文档盖章
2021-07-08 21:18:00
![](https://img.aspxhome.com/file/2023/3/93463_0s.jpg)