高级特性

一、切片
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']

未完。。。。。待续。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值