先从昨日未完成的部分开始:
增量赋值运算符
定制序列
class CountList:
def __init__(self, *args):
self.values = [x for x in args]
self.count = {}.fromkeys(range(len(self.values)), 0)
def __len__(self):
return len(self.values)
def __getitem__(self, item):
self.count[item] += 1
return self.values[item]
c1 = CountList(1, 3, 5, 7, 9)
c2 = CountList(2, 4, 6, 8, 10)
print(c1[1]) # 3
print(c2[2]) # 6
print(c1[1] + c2[1]) # 7
print(c1.count)
# {0: 0, 1: 2, 2: 0, 3: 0, 4: 0}
print(c2.count)
# {0: 0, 1: 1, 2: 1, 3: 0, 4: 0}
fromkeys()方法语法:
dict.fromkeys(seq[, value])
参数
- seq -- 字典键值列表。
- value -- 可选参数, 设置键序列(seq)的值。
返回值
该方法返回一个新字典。
实例
以下实例展示了 fromkeys()函数的使用方法:
实例(Python 2.0+)
#!/usr/bin/python # -*- coding: UTF-8 -*- seq = ('Google', 'Runoob', 'Taobao') dict = dict.fromkeys(seq) print "新字典为 : %s" % str(dict) dict = dict.fromkeys(seq, 10) print "新字典为 : %s" % str(dict)
以上实例输出结果为:
新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None} 新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}
4.10 生成器
- 在 Python 中,使用了
yield
的函数被称为生成器(generator)。 - 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。
- 在调用生成器运行的过程中,每次遇到
yield
时函数会暂停并保存当前所有的运行信息,返回yield
的值, 并在下一次执行next()
方法时从当前位置继续运行。 - 调用一个生成器函数,返回的是一个迭代器对象。
【例子】用生成器实现斐波那契数列。
def libs(n):
a = 0
b = 1
while True:
a, b = b, a + b
if a > n:
return
yield a
for each in libs(100):
print(each, end=' ')
# 1 1 2 3 5 8 13 21 34 55 89
宝可梦数据分析-平民最强宝可梦选择方案
从相关性热力图中,能得到什么信息?
种族值这段代码是什么操作含义?(特征类型转化是怎么做的)
for c in interested:
df[c] = df[c].astype(float)
df = df.assign(total_stats = df[interested].sum(axis=1))