python中for循环的用法_浅谈Python的for循环
for循环在python中的重要性毋庸置疑,可是,我们真的把所有for循环的知识点都理解透了么?试试看以下内容:
- for 循环的基本格式
for
iterable是可迭代对象,包括字符串,列表,元组,字典,集合,迭代器,列表生成式,生成器。itervar是可迭代对象每次调用__next__方法返回的一个元素。else子句是可选。
2. 迭代字符串
output_list = []# 迭代字符串 - 最简单最常用版本this_str = 'it is a string'for char in this_str:output_list.append(char)print(output_list) #out:['i', 't', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']#使用分片和下标迭代字符串output_list.clear()for index in range(len(this_str)):char = this_str[index:index+1:1]output_list.append(char)print(output_list) #out:['i', 't', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']#改进版本,采用enumerate函数,生成下标output_list.clear()for index, char in enumerate(this_str):output_list.append(this_str[index]) #等效:output_list.append(char)print(output_list)
3. 迭代列表
# 迭代列表output_list = []this_list = ['a', 'b', 'c', 1, 2, 3]for el in this_list:output_list.append(el)print(output_list) #out:['a', 'b', 'c', 1, 2, 3]
4. 迭代元组
# 迭代字元组output_list = []this_tuple = ('a', 'b', 'c', 1, 2, 3)for el in this_tuple:output_list.append(el)print(output_list) #out:['a', 'b', 'c', 1, 2, 3]
5. 迭代字典
# 迭代字典。使用items方法返回key和valuethis_dict = {0: 'a', 1: 'b', 2: 'c', 3: '1', 4: '2', 5: '3'}for key, value in this_dict.items():print('%s:%s' % (key, value))#获取key 使用keys方法获取keyfor key in this_dict.keys():print('key is:%s' % key)#获取value 使用values方法获取valuefor value in this_dict.values():print('value is:%s' % value)
6. 迭代集合
# 迭代集合output_list = []this_set = {'a', 'b', 'c', 1, 2, 3}for el in this_set:output_list.append(el)print(output_list) #out:[1, 2, 3, 'b', 'c', 'a']
7. 迭代列表生成式,通常用于从一个列表推导出另外一个列表(筛选,操作)
# 迭代列表生成式 从一个列表推导到另外一个列表,所有元素都*2this_list = ['a', 'b', 'c', 1, 2, 3]output_list = []for el in [x * 2 for x in this_list]:output_list.append(el)print(output_list) #out:'aa', 'bb', 'cc', 2, 4, 6]# 迭代列表生成式 从一个列表筛选到另外一个列表,只要是字符串的元素output_list.clear()for el in [x for x in this_list if type(x) is str]:output_list.append(el)print(output_list) #out:['a', 'b', 'c']
8. 迭代生成器
# 迭代生成器 方法一 使用类似列表生成器的方式output_list = []for el in (num * 2 for num in range(10)):output_list.append(el)print(output_list) #out:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]# 迭代生成器 方法二 自定义一个函数并且用yield返回def get_number(max_num: int):for num in range(max_num):yield num * 2output_list = []for el in get_number(10):output_list.append(el)print(output_list) # out:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
9. 如何在迭代过程中移除元素(列表和字典)
我们先看看python手册是怎么说在迭代中移除元素的:
我们试试看:
this_list = ['a', 'b', 'c', 1, 2, 3]#迭代中删除列表元素 和期待的输出结果不同!!for el in this_list:if type(el) is str:this_list.remove(el) #out: ['b', 1, 2, 3]
在迭代列表的过程中,移除所有的字符串类型的元素,期望的输出结果是[1,2,3],为什么是 ['b', 1, 2, 3]?因为,移除了元素以后,就破坏了计数器,在列表中也是通过计数器来索引的。所以我们可以这么做:
this_list = ['a', 'b', 'c', 1, 2, 3]#使用副本来进行迭代,用原本来进行删除for el in this_list[:]: #this_list[:]是用切片生成this_list的一个副本if type(el) is str:this_list.remove(el) #out: [1, 2, 3]
再试试字典:
this_dict = {0: 'a', 1: 'b', 2: 'c', 3: '1', 4: '2', 5: '3', 6: 1, 7: 2}for key, value in this_dict.items():if type(value) is str:del(this_dict[key]) #RuntimeError: dictionary changed size during iteration
可以这样写,遍历字典的key列表,同时根据key来删除元素
this_dict = {0: 'a', 1: 'b', 2: 'c', 3: '1', 4: '2', 5: '3', 6: 1, 7: 2}for key in list(this_dict.keys()):if type(this_dict[key]) is str:del(this_dict[key]) #output: {6: 1, 7: 2}
希望这文章能帮到你。
python中for循环的用法_浅谈Python的for循环相关推荐
- python中的date的含义_浅谈python中的dateime
原文链接:http://www.cnblogs.com/lhj588/archive/2012/04/23/2466653.html Python提供了多个内置模块用于操作日期时间,像calendar ...
- python中异或怎么算_浅谈Python逻辑运算符 异或xor
我又来水文章了 这篇讲讲令人百思不得骑姐的异或运算 让我们先来看两段,不,是10(b)段对话:技术员:这个水坝系统的设计思路为按下紧急按钮或者水位高于危险水位时,系统发出警报 提问者:这个" ...
- python中astype用法_浅谈python 中的 type(), dtype(), astype()的区别
如下所示: 函数 说明 type() 返回数据结构类型(list.dict.numpy.ndarray 等) dtype() 返回数据元素的数据类型(int.float等) 备注:1)由于 list. ...
- python的re2和re区别_浅谈Python中re.match()和re.search()的使用及区别
1.re.match()fvk免费资源网 re.match()的概念是从头匹配一个符合规则的字符串,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None.fvk免费资源网 包含的参数如下: ...
- python老是报参数未定义_浅谈Python程序的错误:变量未定义
Python程序的错误种类 Python程序的错误分两种.一种是语法错误(syntax error).这种错误是语句的书写不符合Python语言的语法规定.第二种是逻辑错误(logic error). ...
- python 读excel字符型 数值_浅谈python 读excel数值为浮点型的问题
浅谈python 读excel数值为浮点型的问题 如下所示: #读入no data = xlrd.open_workbook("no.xlsx") #打开excel table = ...
- python中while语句的用法_全面解析Python的While循环语句的使用方法
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件: 执行语句-- 执行语句可以是单个语句或语句 ...
- python 报错traceback怎么解决_浅谈python出错时traceback的解读
写 Python 代码的时候,当代码中出现错误,会在输出的时候打印 Traceback 错误信息,很多初学者看到那一堆错误信息,往往都会处于懵逼状态,脑中总会冒出一句,这都是些啥玩意.如果你是第一次 ...
- python中for循环和while循环的区别_浅谈python中的while循环
python中有两种循环,while和for,两种循环的区别是,while循环之前,先判断一次,如果满足条件的话,再循环:for循环的时候必须有一个可迭代的对象,才能循环,比如说 列表.字典.字符串等 ...
最新文章
- 【抬杠】在某些时候不希望用户缩小浏览器的宽度,因为咳咳~会导致你的布局混乱,那么这个代码就是帮助你如何限制浏览器宽度的
- 五行塔怎么吃第五个_红毛丹怎么吃 吃红毛丹的五个好处
- js立即调用的函数表达式
- dram和nand哪个难生产_草缸能不能用陶粒,看完和水草泥的对比,你就知道哪个更好了...
- mysql独立服务器_独立服务器linux系统mysql设置方法
- java null布局_Java中的null布局
- Unix环境高级编程(十五)高级I/O
- 2018年内蒙古开出4.93亿环保罚单
- 推荐几个清华和交大学霸公众号,值得学习
- XVIII Open Cup named after E.V. Pankratiev. Grand Prix of Saratov
- 毕业论文尾注和参考文献
- 快速故障定位 看联想和Riverbed如何演绎?
- MYSQL函数group_concat的使用
- php 文本域,关于使用文本域(TextArea)的一个问题
- 微软Visio流程图软件,Visio流程图制作工具下载安装教程(1)
- 如何实现表格行列冻结
- 产品经理(20) #PRD产品需求文档
- git命令行修改用户名密码
- 使用Python将OV7725的RGB565图像数据转换为jpg图像
- 开发者方案 · 久坐提醒 / 喝水提醒小助手·树莓派4B/咕咕机G2/涂鸦 Link SDK