YangDongJae
YangDongJae

Reputation: 105

python comprehension with dict covert to don't use comprehension

this source code is use comprehension in python

hidden_layer = [{'weights':[random() for i in range (3)]} for i in range(1)]

so i transform to don't use comprehension expression and below is my source code to transform that

import random 

for i in range(3):
     for i in range (1):
          hidden_layer = {'weights':random()}

but it just have a only one value in dictionary

what am i missing?

Upvotes: 1

Views: 35

Answers (2)

kennysliding
kennysliding

Reputation: 2977

A personal trick for me to unwrap list compression is to always start from the most outer layer to the inner layer.

To demonstrate with your code:

from random import random
hidden_layer = [{'weights':[random() for i in range (3)]} for i in range(1)]
print(hidden_layer)

As we see the most outer layer is a list, I would initialize a list for that first, then push the inner comprehension one by one

from random import random
hidden_layer = []
for i in range(1):
    hidden_layer.append({'weights':[random() for i in range (3)]})
print(hidden_layer)

Next, we can further unwrap the inner layer, the tricks is the identify the index as the same index in nest comprehension won't interrupt your loop, but definitely will in a normal 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)

And there we go!

Upvotes: 1

Boseong Choi
Boseong Choi

Reputation: 2596

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)

output:

[{'weights': [0.4708113985288851, 0.861100368435909, 0.7732951090293462]}]

Upvotes: 1

Related Questions