python(三)高级特性


判断一个对象可不可以迭代

切片

1
2
3
4
5
6
7
collect = ["a","b","c","d","e"]
print(collect[:3]) # 取前三个
print(collect[0:3]) # 取前三个
print(collect[-2:]) # 取最后两个
print(collect[:]) # 复制一个原样的list
collectTuple=(1,2,3,4,5)
print(collectTuple[0:3]) #取出tuple的前三个

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from collections import Iterable
myDict = {"a":"1","b":"2","c":"3","d":"4"}

for value in collect:
print("普通的迭代:"+value)

for key in myDict:
print("Dict的迭代 key :" + key)

for value in myDict.values():
print("Dict的迭代 value :" + value)

for key,value in myDict.items():
print("Dict的迭代 key 和 value :" +key+"...."+ value)

for myChar in "ABC":
print("迭代字符串中的字符:"+myChar)

for i,value in enumerate([1,2,3,45]):
print("i的索引是%s,value的值是%s"%(i,value)) #格式化输出

print(isinstance("ABC",Iterable)) # 判断一个对象可不可以迭代,需要引包
print(isinstance([1,2,3,4],Iterable)) # 判断一个对象可不可以迭代,需要引包

列表生成式

1
print([ x*x for x in  range(1,11) if x%2==0])