Kamil Sindi
Kamil Sindi

Reputation: 22822

Elegant way to manipulate lists within list?

EDIT: I've changed my question slightly to make it more general whereby the i in p[i][j] can also change.

Very new to Python. I have lists [of equal length] within a list, which makes a 4 row by 5 column grid:

p = [[1.0, 3.0, 4.0, 1.0, 1.0],
     [1.0, 1.0, 5.0, 1.0, 1.0],
     [1.0, 6.0, 6.0, 1.0, 1.0],
     [1.0, 4.0, 1.0, 1.0, 6.0]]

To manipulate each cell, what I'm doing now is this:

for i in range(len(p)):
    for j in range(len(p[0])):
        p[i][j] = p[i][j - 1] * c1 + p[(i + 1) % len(p)][j] * c2

My question is: Is there a more elegant way to write this instead of having a for loop within another for loop? Perhaps using lambda?

Upvotes: 2

Views: 176

Answers (3)

alexis
alexis

Reputation: 50190

If you don't want two nested loops, you can loop over the rows and construct each replacement row using a "list comprehension" (which also happens to use the keyword for):

for i in range(len(p)):
    p[i] = [ p[i][j-1]*c1 + p[i][j] * c2 for j in range(len(p[0])) ]

Since you're new to python, I'll add some suggestions:

a) There's nothing wrong with using two nested for-loops. In my opinion they are the best (clearest, most elegant) way to write your example.

b) You do realize that 1%len(p[0]) is a constant, right? But you probably don't realize that row[i- 1%len(row)] == row[i-1] EVEN in the case where p only has one column (because of the way index -1 works)

c) Somebody made the good suggestion to look at numpy Arrays (but then deleted the answer). I second it.

Upvotes: 2

Marcin
Marcin

Reputation: 49826

You can iterate without using indices:

for row in p:
    for j in range(len(row)):
        row[j] = row[j - 1 % len(row)] * c1 + row[j] * c2

I leave it to you to decide if there is a better way for you to operate on a single row.

If you want to cross-refer between rows and columns, then no, there's no especially better way to do this, unless you want to use something like numpy.

Upvotes: 2

Tomislav Dyulgerov
Tomislav Dyulgerov

Reputation: 1026

Using a combination of map and lambda might do the trick.

Upvotes: 0

Related Questions