Python高级特性——迭代(Iteration)
生活随笔
收集整理的這篇文章主要介紹了
Python高级特性——迭代(Iteration)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python高級特性——迭代(Iteration)
>>> l=[3,6,4,8,1,0]
>>> find(l)
(0, 8)
>>> l=[]
>>> find(l)
(None, None)
1、給定一個集合list或者tuple,可以通過for …… in ……的語法來實現循環遍歷,這個循環我們就叫做迭代
迭代list:
>>> m = ['haha','hehe','heihei','gaga'] >>> for li in m: ... print(li) ... haha hehe heihei gaga迭代字符串:
>>> n = 'abcdefg' >>> for str in n : ... print(str) ... a b c d e f g迭代dict,迭代key
>>> l = {'name':'wuchong','age':15} >>> for dic in l: ... print(dic) ... name age迭代value:
>>> for dic in l.values(): ... print(dic) ... wuchong 15同時迭代key、value:
>>> for key,value in l.items(): ... print(key,value) ... name wuchong age 15Python中,只要是可迭代對象,都可以迭代。
那么,如何判斷一個對象是不是可迭代對象呢?方法是通過collections中的Iterable類型判斷。
>>> from collections import Iterable >>> isinstance('123',Iterable) True >>> isinstance([1,2,3],Iterable) True >>> isinstance(123,Iterable) False可知,整數類型不是可迭代類型。
通過Python內置的enumerate函數可以把一個list變成索引-元素對的形式:
>>> m ['haha', 'hehe', 'heihei', 'gaga'] >>> for dx,value in enumerate(m): ... print(dx,value) ... 0 haha 1 hehe 2 heihei 3 gaga練習:使用迭代從一個list中查詢最大值和最小值,如果list為None,返回[None,None],并返回一個tuple
>>> def find(l): ... if l==[]: ... return (None,None) ... else: ... min = max = l[0] ... for i in l: ... if i<min : ... min = i ... if i>max: ... max = i ... return (min,max)>>> l=[3,6,4,8,1,0]
>>> find(l)
(0, 8)
>>> l=[]
>>> find(l)
(None, None)
?
posted on 2017-12-17 18:30 風雨一肩挑 閱讀(...) 評論(...) 編輯 收藏轉載于:https://www.cnblogs.com/hiwuchong/p/8052818.html
總結
以上是生活随笔為你收集整理的Python高级特性——迭代(Iteration)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS - block变量捕获原理
- 下一篇: Windows 7 下右键发送到菜单项没