Python基础回顾

2018-05-23  本文已影响0人  keepWhat

@ 基本类型

>>> type(1)
<class 'int'>
>>> type(1.2)
<class 'float'>
>>> type([1])
<class 'list'>
>>> type((1,))
<class 'tuple'>
>>> isinstance(1,int)
True
>>> isinstance(1,float)
False
>>> type({1,'a'})
<class 'set'>
>>> type({1:'a'})
<class 'dict'>
>>>

@异常处理

>>> try:
...     1/0
... except Exception as e:
...     print(e)
... else:
...     pass
... finally:
...     print('end')
...
division by zero
end
>>>

@快速排序

@字典推导式

>>> {k: v for (k,v) in enumerate([1,2,3])}
{0: 1, 1: 2, 2: 3}

@字符串格式化

%format

>>> "fadf%d%s" %(1,'a')
'fadf1a'
>>> "fadf{}{}".format(1,'a')
'fadf1a'

@迭代器和生成器

fibonacci代码

>>> l=[x*x for x in range(2)]
>>> l
[0, 1]
>>> g=(x*x for x in range(2)) # generator
>>> g
<generator object <genexpr> at 0x1038f69b0>
>>> next(g)  # next下一个值
0
>>> next(g)
1
>>> next(g) # 直到抛出StopIteration
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> for i in (x*x for x in range(2)): # generator是可迭代对象
...     print(i)
...
0
1
>>> hasattr(g,'__iter__')
True

可迭代对象(iterable):list, dict, str, generator, tuple

>>> from collections import Iterable # 使用isinstance判断是否是iterable(可迭代对象,可以用于for循环)
>>> isinstance([],Iterable) # list
True
>>> isinstance({},Iterable) # dict
True
>>> isinstance('abc',Iterable) # str
True
>>> isinstance((x for x in range(2)), Iterable) # generator
True
>>> isinstance((1,), Iterable) # tuple
True
>>> isinstance(11, Iterable) # int
False

iterator:
可以被next()函数调用并不断返回下一个值的对象称为迭代器(Iterator)

# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False
# 把list、dict、str等Iterable变成Iterator可以使用iter()函数:
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True
>>> t='abc'
>>> next(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: str object is not an iterator
>>> t=iter(t)
>>> next(t)
'a'
>>> next(t)
'b'
>>>

小结

  1. 凡是可作用于for循环的对象都是Iterable类型;
  2. 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
  3. 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
  4. Python的for循环本质上就是通过不断调用next()函数实现的

@遍历

>>> d={'a':1,'b':2,'c':3}
>>> for i in d: # 直接遍历字典,遍历的是key
...     print(i)
...
a
c
b
>>> for k,v in d.items(): # 使用items()遍历键值对
...     print('{}->{}'.format(k,v))
...
a->1
c->3
b->2
>>> for i in [1,2]: # 遍历列表
...     print(i)
...
1
2
>>> for index,value in enumerate([1,2]): #遍历列表(带索引)
...     print('{}->{}'.format(index,value))
...
0->1
1->2

@copy()和deepcopy()

pass

@读写文件

read,readline和readlines

上一篇下一篇

猜你喜欢

热点阅读