天天看點

python——進階特性(2)

疊代

在python中疊代是通過for ....in...完成的,隻要是可疊代對象都可以疊代

#!usr/bin/python
#-*- coding:UTF-8 -*-

#tuple疊代
t=[(1,'a','z'),(2,'b','z')]for x,y,z in t:
    print(x,z)

#enumerate函數可以把一個list或者tuple變成“索引-元素”對
for i,value in enumerate(t):
    print(i,value)

》1 z
》2 z

》0 (1, 'a', 'z')
》1 (2, 'b', 'z')      

注意:這裡輸出的其實是tuple(括号省略掉了)

預設情況下,dict疊代的是key。如果要疊代value,可以用

for value in d.values()

,如果要同時疊代key和value,可以用

for k, v in d.items()

#dict的疊代
d={'city':'SH','age':12,'sex':'G'}
for k in d.items():
    print(k)

輸出》
('city', 'SH')
('age', 12)
('sex', 'G')      

判斷

那麼,如何判斷一個對象是可疊代對象呢?方法是通過collections子產品的Iterable類型判斷:

#Iterable類型判斷 使用isinstance函數
from collections import Iterable
#str是否可以疊代
print('str是否可以疊代',isinstance('abc',Iterable))
#list是否可以疊代
print('list是否可以疊代',isinstance([1,2,3],Iterable))
#整數是否可以疊代
print('整數是否可以疊代',isinstance(123,Iterable))

輸出》
str是否可以疊代 True
list是否可以疊代 True
整數是否可以疊代 False      

使用疊代

使用疊代傳回一個list的最小值和最大值

#使用疊代找到list中的最小值和最大值并傳回
def findMinAndMax(L):
    if L==[]:
        return (None,None)
    min=max=L[0]
    for n in L:
        if min>n:
            min=n
        if max<n:
            max=n
    return (min,max)

print(findMinAndMax([1,3,4,55,2]))
》(1, 55)      

清單生成式

清單生成式即List Comprehensions,是Python内置的非常簡單卻強大的可以用來建立list的生成式。寫清單生成式要把元素放在前面,後面for...in...,後面可以加i判斷,比如:

#清單生成式
li=[x*x for x in range(1,11) if x%2==0]
print(li)

》[4, 16, 36, 64, 100]      

應用

運用它可以寫出非常簡潔的代碼,例如列出目前目錄下所有的檔案和目錄名,可以通過一行代碼實作:

import os#導入os子產品
print([s for s in os.listdir('.')])

》['DLLs', 'Doc', 'include', 'iter.py', 'Lib',
 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe',
 'python3.dll', 'python36.dll', 'pythonw.exe', 
'README.txt', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']      

清單生成式也可以添加if語句

通過添加if語句将list中的字元串小寫

# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2=[s.lower() for s in L1 if isinstance(s,str)]
print(L1)
print(L2)

》['Hello', 'World', 18, 'Apple', None]
》['hello', 'world', 'apple']      

生成器

在Python中,這種一邊循環一邊計算的機制,稱為生成器:generator。

未完待續。。。