今天内容大多比较容易,简单的记录一下。
内置序列类型
按照存放类型分类不同类型的数据:list, tuple, collections.deque
一种类型的数据:str, bytes, bytearray, memoryview和arrray.array
按照是否修改分类可变序列:list, bytearray, array.array, collections.deque和memoryview
不可变序列:tuple, str和bytes
列表推导
列表推导
与filter和map使用,举个例子求一个字符串里ascii大于127字符
symbols = '$¢£¥€¤'
print(list(filter(lambda c: c > 127, map(ord, symbols))))
生成器表达式
生成器表达式背后遵守迭代器协议,可以逐个地产出元素,显然节省内存,生成器表达式的语法跟列表推导差不多,只不过把方括号换成圆括号。
print((ord(symbol) for symbol in symbols))
元组
用元组作为字段
元组拆包平行赋值
>>> x = (6, 9)
>>> a, b = x
>>> a
6
>>> b
9用*拆开作为函数参数
>>> t = (20, 8)
>>> divmod(*t)
(2, 4)用*处理剩下的元素,可以出现在赋值表达式任意位置
>>> a, b, *rest = range(5)
>>> a
0
>>> b
1
>>> rest
[2, 3, 4]
嵌套元组拆包
metro_areas = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)), #
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas: #
if longitude <= 0: #
print(fmt.format(name, latitude, longitude))
注意: 元组已经设计得很好用了,但作为记录来用的话,还是少了一个功能:我们时常会需要给 记录中的字段命名。 namedtuple 函数的出现帮我们解决了这个问题。
具名元组
>>> City = namedtuple('City', 'name country population coordinates')
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> tokyo.name
'Tokyo'
>>> tokyo.country
'JP'
>>> tokyo.coordinates
(35.689722, 139.691667)
学习 _fields, _make(), _asdict()
>>> City._fields
('name', 'country', 'population', 'coordinates')
>>> LatLong = namedtuple('LatLong', 'lat long')
>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
>>> City('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
City(name='Delhi NCR', country='IN', population=21.935, coordinates=LatLong(lat=28.613889, long=77.208889))
>>> delhi = City._make(delhi_data)
>>> delhi._asdict()
OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population', 21.935), ('coordinates', LatLong(lat=28.613889, long=77.208889))])元组与列表的区别
切片
给切片赋值
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[2:5] = ["xi","xi"]
>>> l
[0, 1, 'xi', 'xi', 5, 6, 7, 8, 9]
>>> del l[5:7]
>>> l
[0, 1, 'xi', 'xi', 5, 8, 9]
>>> l[3::2] = [11, 22]
>>> l
[0, 1, 'xi', 11, 5, 22, 9]
>>> l[2:5] = 100
Traceback (most recent call last):
File "", line 1, in
TypeError: can only assign an iterable
>>> l[2:5] = [100]
>>> l
[0, 1, 100, 22, 9]
对序列使用+和*
注意下面两种的区别
>>> [[0] * 3] * 3
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> [[0] * 3 for i in range(3)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
第一种,外面的列表包含了3个指向同一个列表的引用,修改一个,其他位置也会修改
序列的增量赋值
_iadd :就地加法(+=) _add
list.sort方法和内置函数sorted
list.sort方法会就地排序列表,也就是说不会把原列表复制一份。
两个关键词参数:reverse,key
当列表不是首选时
数组(array.array)
当只包含数字的列表,那么array.array比list更高效
还有Numpy和 SciPy
还有 deque heapq ....
一定要坚持一下,干!