Rade Tomovic
Rade Tomovic

Reputation: 328

Nested list iterations

I have some list in Python, with nested lists named otherElem which looks like:

otherElem=[[list1],[list2],...[list_n]]

What I need is to create new list which will perform some operations (that's j.Mirror is irrelevant, can be anything) and create a new list which will maintain order and format of previous list. I've tried this, but didn't succeed. I'm totally new in programming, sorry for typos (if any)

for i in otherElem:
        for j in i:
            j=j.Mirror(mirPlane)
            newList.Add(j)
        newList2.Add(newList)

Upvotes: 1

Views: 120

Answers (4)

greatghoul
greatghoul

Reputation: 1538

You can use operator to invoke a nice nested call.

import operator

upper = operator.methodcaller('upper')
list =[['a', 'b', 'c', 'd'],['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
print [map(upper, sub_list) for sub_list in list]
# [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']]

Upvotes: 1

jwilner
jwilner

Reputation: 6606

The other answers are right; a list comprehension is probably the best way to do this in Python. Meanwhile, it specifically looks like what's wrong with your listed solution is that it needs to create a new list each time it looks at an inner list. It should look like:

new_list_of_lists = [] 
for old_list in old_list_of_lists:
   new_list = []
   new_list_of_lists.append(new_list)
   for old_item in old_list:
      new_item = transformation(old_item) 
      new_list.append(new_item)

Those seven lines are completely equivalent to the much shorter nested list comprehensions, so you can see why those comprehensions are preferable!

Upvotes: 1

pnv
pnv

Reputation: 3135

It can be done with nested list comprehension, something like this.

otherElem=[[1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12]]

l = [[an_elem * 2 for an_elem in inner_list] for inner_list in otherElem]

print l

Result is,

[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]

Here, the operation on each element is multiply by 2. in your case it's j.Mirror(mirPlane), which I don't know, what it returns.

Upvotes: 1

shx2
shx2

Reputation: 64298

The inner loop can easily be written as a list comprehension:

[ j.Mirror(mirPlane) for j in i ]

And so can the outer loop:

[ <inner part here> for i in otherElem ]

Putting it together, we get a nested list comprehension:

newList2 = [
  [ j.Mirror(mirPlane) for j in i ]
  for i in otherElem
]

Upvotes: 0

Related Questions