此源代码在python 中使用理解
hidden_layer = [{'weights':[random() for i in range (3)]} for i in range(1)]
所以我转换为不使用理解表达式,下面是我转换的源代码
import random
for i in range(3):
for i in range (1):
hidden_layer = {'weights':random()}
但它在字典中只有一个值
我错过了什么?
from random import random
hidden_layer = []
for i in range(1):
weights = []
for j in range(3):
weights.append(random())
hidden_layer.append({'weights': weights})
print(hidden_layer)
输出:
[{'weights': [0.4708113985288851, 0.861100368435909, 0.7732951090293462]}]
我打开列表压缩的一个个人技巧是始终从最外层开始到内层。
用代码演示:
from random import random
hidden_layer = [{'weights':[random() for i in range (3)]} for i in range(1)]
print(hidden_layer)
正如我们所看到的,最外层是一个列表,我会首先初始化一个该列表,然后逐个推动内部理解
from random import random
hidden_layer = []
for i in range(1):
hidden_layer.append({'weights':[random() for i in range (3)]})
print(hidden_layer)
接下来,我们可以进一步打开内层,技巧是在嵌套理解中将索引识别为同一索引不会中断循环,但在正常的for-loop
中肯定会中断
from random import random
hidden_layer = []
for i in range(1):
new_dict = {'weights': []}
for j in range (3): # remember to use different index variable
new_dict['weights'].append(random())
hidden_layer.append(new_dict)
print(hidden_layer)
我们开始了!