1

I'm trying to do an inline uniform distribution initialization, but don't seems to find how to do so, if possible.

My working code is:

test = [[1,2,3],[4,5,6],[7,8,9]]
p = []
for row in test:
    prow = [1.0/(len(row)*len(test)) for x in row]
    p.append(prow)
print p
[[0.1111111111111111, 0.1111111111111111, 0.1111111111111111],
 [0.1111111111111111, 0.1111111111111111, 0.1111111111111111],
 [0.1111111111111111, 0.1111111111111111, 0.1111111111111111]]

My question is, is there a way to narrow the "for row in test" to the same form of the second loop and end up with only 1 line? Something like:

p = [1.0/(len(row)*len(test)) for x in row for row in test]
print p
[0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111,
 0.1111111111111111]

But obviously the right result. Clues?

mimoralea
  • 9,590
  • 7
  • 58
  • 59

2 Answers2

4

I think something like:

[[1.0/(len(row)*len(test))]*len(row) for row in test]

if I'm reading your code correctly. The magic here is because every element in the row gets the same (immutable) value, you can just create a list of the correct length with the correct value ala [value]*length.

mgilson
  • 300,191
  • 65
  • 633
  • 696
3

Yeah, what you're looking for is this:

In [13]: test = [[1,2,3],[4,5,6],[7,8,9]]

In [14]: p = [[1.0/(len(row)*len(test)) for x in row] for row in test]

In [15]: p
Out[15]: 
[[0.1111111111111111, 0.1111111111111111, 0.1111111111111111],
 [0.1111111111111111, 0.1111111111111111, 0.1111111111111111],
 [0.1111111111111111, 0.1111111111111111, 0.1111111111111111]]

PS: You might be interested in list comprehension syntax

Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241