模块 collections-collections.namedtuple 表示 tuple 欲言不清
如表示一个坐标, t = (1,2), 搞不清楚.
如果这样就对了 Point(x=1, y=2)
- from collections import namedtuple
- Point = namedtuple('Point', ['x', 'y']) #做一些 kv 形式的易辨别的数据结构
- p = Point(1, 2)
- print(p)
- # Point(x=1, y=2)
类的方法: getitem 把实例当 list 来操作
- class Student:
- arr = [0, 1, 2, 3, 4] #返回 arr 的第 3 项
- def __getitem__(self, n):
- return self.arr[n]
- s = Student()
- print(s[3])
- # 3
类的方法: __len__方法用于丈量类的实例的长度
- class A:
- arr = [1, 2, 3] #返回他的长度
- def __len__(self):# 用来丈量实例长度的
- return len(self.arr)
- a = A()
- print(len(a))
- # 3
一些小知识点
- str 转 list
- >>> list('JQKA')
- ['J', 'Q', 'K', 'A']
- 生成 str 类型的数字序列
- >>> [str(n) for n in range(2,11)]
- ['2', '3', '4', '5', '6', '7', '8', '9', '10']
综合小例子
- from collections import namedtuple
- Point = namedtuple('Point', ['x', 'y'])
- p = Point(1, 2)
- print(p)
- arr1 = [str(i) for i in range(10)]
- arr2 = [str(i) for i in range(10)]
- s = [Point(k1,k2) for k1 in arr1 for k2 in arr2]
- print(s)
- # Point(x=1, y=2)
- # [Point(x='0', y='0'), Point(x='0', y='1'), Point(x='0', y='2'), Point(x='1', y='0'), Point(x='1', y='1'), Point(x='1', y='2'), Point(x='2', y='0'), Point(x='2', y='1'), Point(x='2', y='2')]
[py][lc]python 的纸牌知识点
来源: http://www.bubuko.com/infodetail-2490995.html