高級特性

一、切片
1.可以切片的數據類型

注意:字典和集合不支持切片,因爲它們都是無續的數據類型
二、迭代
1.判斷一個對象是否可迭代的方法

  • 是否可用for循環遍歷
  • isinstance()方法
In [6]: from collections import Iterable

In [7]: isinstance("hello", Iterable)   #字符串時是迭代對象
Out[7]: True

In [8]: isinstance((1,2,3), Iterable)   #元組是可迭代對象
Out[8]: True

In [9]: isinstance([1,2,3], Iterable)   #列表是可迭代對象
Out[9]: True

In [10]: isinstance({a:1}, Iterable)    #字典是可迭代對象
Out[10]: True 

In [11]: isinstance({1,2,3}, Iterable)  #集合是可迭代對象
Out[11]: True

2.for循環迭代
以字典爲例:

In [13]: d = {'a': 1, 'b': 2, 'c': 3}

In [14]: for key in d:
   ....:     print key
   ....:     
a
c
b

默認情況先迭代字典的key,如果要迭代value,可以用下面的方法

In [15]: d = {'a': 1, 'b': 2, 'c': 3}

In [16]: for value in d.values():
    print value
   ....:     
1
3
2

三、列表生成器
1.列表生成式即List Comprehensions,是Python內置的非常簡單卻強大的可以用來創建list的生成式
以生成[1x1, 2x2, 3x3, …, 10x10]list爲例:

  • 方法一
list = []
for i in range(1,11):
    list.append(i*i)
print list
  • 方法二
print [i**2 for i in range(1,11)]

2.變異的列表生成式

  • .for 循環嵌套 if 語句的列表生成式
    找出1-10內的所有偶數
print [i for i in range(1,11) if i%2 == 0]

運行效果:
[2, 4, 6, 8, 10]
  • for 循環嵌套 for 循環 , 兩個字符串的全排列
print [i+j for  i in "abc" for j in "def"]

運行效果:
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']

test:找出/etc下以“.conf”結尾的文件,並顯示前五個

>>> import os
>>> [ i for i in os.listdir("/etc") if i.endswith(".conf")][:5]
['resolv.conf', 'extlinux.conf', 'mtools.conf', 'libuser.conf', 'idmapd.conf']

未完。。。。。待續。。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章