0%

Python解析式推导式

[ 值 for 元素 in 可迭代对象 if 条件 ] # 值可以是函数表达式

[ 值1 if 条件1 else 值2 for 元素 in 可迭代对象] # 将 if-else 语句写入列表解析式

1
2
3
4
5
6
7
8
9
10
11
ret = [0.37, -1.9, 0.6, 2.54, 0.51, 1.09, 1.79, -1.2, -0.14, -0.5, -2.37, 0.0, -0.22, -0.15, 4.28, -0.85, -1.79, -0.44, -0.15, 2.34]

# 例:从收益率序列中提取出负的收益率
[i for i in ret if i < 0]

[-1.9, -1.2, -0.14, -0.5, -2.37, -0.22, -0.15, -0.85, -1.79, -0.44, -0.15]

# 正收益率赋值为1,负收益率赋值为0
[1 if i > 0 else 0 for i in ret]

[1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
1
2
3
4
ret_set = {(0.37, -1.9, 0.6, 2.54, 0.51), (1.09, 1.79, -1.2, -0.14, -0.5), (-2.37, 0.0, -0.22, -0.15, 4.28), (-0.85, -1.79, -0.44, -0.15, 2.34)}

# 如何将元素打平
[i for t in ret_set for i in t]

内循环在外循环后面