python中for循环的用法_浅谈Python的for循环
生活随笔
收集整理的這篇文章主要介紹了
python中for循环的用法_浅谈Python的for循环
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
for循環(huán)在python中的重要性毋庸置疑,可是,我們真的把所有for循環(huán)的知識點(diǎn)都理解透了么?試試看以下內(nèi)容:
iterable是可迭代對象,包括字符串,列表,元組,字典,集合,迭代器,列表生成式,生成器。itervar是可迭代對象每次調(diào)用__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']#使用分片和下標(biāo)迭代字符串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']#改進(jìn)版本,采用enumerate函數(shù),生成下標(biāo)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. 迭代列表生成式,通常用于從一個列表推導(dǎo)出另外一個列表(篩選,操作)
# 迭代列表生成式 從一個列表推導(dǎo)到另外一個列表,所有元素都*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]# 迭代生成器 方法二 自定義一個函數(shù)并且用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手冊是怎么說在迭代中移除元素的:
由于迭代中有計(jì)數(shù)器,不能直接刪除元素我們試試看:
this_list = ['a', 'b', 'c', 1, 2, 3]#迭代中刪除列表元素 和期待的輸出結(jié)果不同!!for el in this_list:if type(el) is str:this_list.remove(el) #out: ['b', 1, 2, 3]在迭代列表的過程中,移除所有的字符串類型的元素,期望的輸出結(jié)果是[1,2,3],為什么是 ['b', 1, 2, 3]?因?yàn)?#xff0c;移除了元素以后,就破壞了計(jì)數(shù)器,在列表中也是通過計(jì)數(shù)器來索引的。所以我們可以這么做:
this_list = ['a', 'b', 'c', 1, 2, 3]#使用副本來進(jìn)行迭代,用原本來進(jìn)行刪除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列表,同時根據(jù)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}希望這文章能幫到你。
總結(jié)
以上是生活随笔為你收集整理的python中for循环的用法_浅谈Python的for循环的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 平安普惠提前结清怎么操作
- 下一篇: 南宁公交车扫码支付怎么用