Tendo Chen
Tendo Chen

Reputation: 31

Basic Python manipulation of nested list

For the following nested list, Lst, I need to keep the first inner list, square the second, and cube the last one.

Lst = [[1,2,3],[2,3,4],[3,4,5]]

My current code is squaring all the nested list in the Lst.

list(map(lambda lst: list(map(lambda x: x**2, lst)), Lst))

How can I fix this? I just started learning Python.

Upvotes: 2

Views: 112

Answers (4)

White Owl
White Owl

Reputation: 21

Try indexing the outer list and then call the map function on each index

def square(number) :
    return number ** 2
def cube(number) :
    return number ** 3

lst = [[1,2,3],[2,3,4],[3,4,5]]

lst[0] = lst[0]
lst[1] = list(map(square, lst[1]))
lst[2] = list(map(cube, lst[2]))

print(lst)

Upvotes: 0

tripleee
tripleee

Reputation: 189936

Your processing obviously needs to take into account where in the list you are. Forcing this into a one-liner makes it more dense than it really needs to be, but see if you can follow along with pencil and paper.

[[x if i == 0 else x**2 if i == 1 else x**3 for x in Lst[i]] for i in range(3)]

Demo: https://ideone.com/o8y0ta

... Or, as cleverly suggested in Barmar's answer,

[[x**i for x in Lst[i]] for i in range(3)]

Upvotes: 0

Barmar
Barmar

Reputation: 782693

Since you're not doing the same operation on each nested list, you shouldn't use map() for the top-level list. Just make a list of results of different mappings for each.

[Lst[0], list(map(lambda x: x**2, lst[1])), list(map(lambda x: x**3, lst[2]))]

However, there's an obvious pattern to this, so you can generalize it using enumerate() and a list comprehension:

[list(map(lambda x: x**i, sublist)) for i, sublist in enumerate(Lst, 1)]

Upvotes: 4

Epsi95
Epsi95

Reputation: 9047

[list(map(lambda x: x**i, l)) for i,l in enumerate(Lst, 1)]
[[1, 2, 3], [4, 9, 16], [27, 64, 125]]

Upvotes: 1

Related Questions