1

I tried to write this, where s is just an int

 for box in current_boxes:
        for i in range(len(box)):
            box[i] = box[i]*s
        all_boxes.append(box)

as a list comprehension. But my result is not the same. That's what I've tried.

all_boxes = [all_boxes.append(box[i]*s) for box in current_boxes for i in range(len(box))]

Any help is much appreciated.

upix
  • 23
  • 4
  • 1
    To clarify, you want `all_boxes` to be a list of lists, where each inner list is a copy of box but with some entries modified? It would be helpful if you include a small example input and the expected output. – MichaelCG8 May 31 '22 at 15:30
  • i wrote out an example myself using setup `current_boxes = [[1], [2], [3, 5]]; s = 1.1; all_boxes = []` but i agree its tricky to get list comp right in this scenario. – rv.kvetch May 31 '22 at 15:33

2 Answers2

2

When using list comprehension you're building a new list. You don't need to use append.

You don't need to use an interator with list indices and range either.

The inner loop would look like this :

[value*s for value in box]

Here we're building a new list which be the original list with each item multiplied by your s variable.

Now, we need to create a such list for each box in your current_boxes.

The outer loop that would do this may be like :

[box for box in current_boxes]

When combined :

all_boxes = [[value*s for value in box] for box in current_boxes]
ibi0tux
  • 2,481
  • 4
  • 28
  • 49
0

This should do the trick

all_boxes =[list(map(lambda y : y*s, box)) for box in current_boxes]

We are using the build in python map() function, it takes in as first argument a function that is applied to each element of the second iterable argument (a list in our case ). the map() returns a iterable so we cast it to 'list' for obtaining the desidered result.

this 'lambda y : y*s' function can be also expressed in this way:

def mult_by_s(element):
    element*s

all_boxes =[list(map(mult_by_s, box)) for box in current_boxes]

but it requires that 's' is global so lambda y : y*s is a better fit in my opinion.

Also another approach is to use only map function to resolve the problem

 all_boxes =list(map(lambda box :list(map(lambda y : y*s, box)), current_boxes))
  • 1
    While this werks, the mixing of styles is a bit odd, and I'm not sure what it gains over nested list comprehensions. – Chris May 31 '22 at 16:17
  • It' just a differt paradigm to solve the problem, also I dont think is the case for python but the map operatin can be parallelized potecially improoving performance, in fact the map/reduce operation are very common for large scale data manipolation in framework like Spark or hadoop-MapReduce – Damiano Nardi May 31 '22 at 16:35