Home > OS >  Lambda editing Nth object of list and return edited list
Lambda editing Nth object of list and return edited list

Time:11-20

I have a list a.

a = [[10,13,14],[34,23,4],[1,6,3]]

Now I want to increase the Nth integer of each sublist in the list.

def increase(sublistOrg):
    sublist = sublistOrg.copy()
    sublist[1]  = 1
    return sublist

aEdited = list(map(increase, a))

Can I replace the additional "increase" function with a lambda expression?

CodePudding user response:

lambda x: [x[i]   1 if i == 1 else x[i] for i in range(len(x))]

This works, but it's probably worse than just using a "normal" function

CodePudding user response:

You can do it with a lambda but it's probably uglier than the solution you have:

aEdited = list(map(lambda x: [element if index != 1 else element   1 for index, element in enumerate(x)], a))
  • Related