你基本上只是向后工作,所以首先你有:
代码 1
{i: [np.random.randint(mins[t], maxs[t]) for t in range(len(mins))] for i in range(k)}
所以第一步是for i in range(k) 生成你的密钥,然后是生成一个列表,或者:
result = {}
for i in range(k):
temp = []
# something to do with making a list
result[i] = temp
然后再次向后工作,您有 for t in range(len(mins)) 只剩下 np.random.randint(mins[t], maxs[t]) 位
所以:
result = {}
for i in range(k):
temp = []
for t in range(len(mins)):
temp.append(np.random.randint(mins[t], maxs[t]))
result[i] = temp
在完整的代码示例中是
import numpy as np
mins = [1, 2, 3, 4]
maxs = [5, 6, 7, 8]
k = 3
test = []
test = {
i: [np.random.randint(mins[t], maxs[t]) for t in range(len(mins))] for i in range(k)
}
print(test)
result = {}
for i in range(k):
temp = []
for t in range(len(mins)):
temp.append(np.random.randint(mins[t], maxs[t]))
result[i] = temp
print(result)
第一个是你的理解,第二个是 for 循环。结果:
{0: [3, 3, 3, 4], 1: [2, 4, 3, 6], 2: [3, 2, 3, 5]}
{0: [4, 3, 4, 4], 1: [3, 3, 4, 4], 2: [3, 2, 6, 4]}
你可以看到我们通过从右到左解构理解得到了相同的结果!
案例2
indices = [distances.index(row) for row in distances if row[-1] == c]
可以用同样的方法分解。从最后面的for 开始,我们发现:
for row in distances if row[-1] == c
相当于:
for row in distances:
if row[-1] == c
#do something
我们知道所有内容都包含在一个列表中,因此添加一个列表并将“某物”附加到其中非常简单:
indices = []
for row in distances:
if row[-1] == c:
indices.append(distances.index(row))
请注意,我还没有测试过这个(而且根据给出的信息也无法测试)
如果我们把这个放到原来的代码块中
for c in range(k):
indices = [distances.index(row) for row in distances if row[-1] == c]
test[c] = X.iloc[indices].mean().values
我们现在有
for c in range(k):
indices = []
for row in distances:
if row[-1] == c:
indices.append(distances.index(row))
test[c] = X.iloc[indices].mean().values