0

I have an array holding another object items :

myarray=[]
myarray.append((1,2,3))
myarray.append((4,5,6))

how can I apply a map function to the last 2 columns of the list somethign like

def inc(x):
  return x+1

then

myarray map (inc) # only to the last 2 columns (2,3) and (5,6)

in short I want to transform the data structure from

((1,2,3))
((4,5,6))

to

((1,3,4))
((4,6,7))

thanks

EDIT: just so others can benfit from this I wrote to functions based on @alef response

def format_sub_list(_list,i):
  return [[y if i < len(x)-i else inc(y)
  for i, y in enumerate(x)]
  for x in _list]

or

def format_sub_list2(_list,sublist):
  return [[y if i in (sublist) else inc(y)
  for i, y in enumerate(x)]
  for x in _list]
2
  • Shall the result be just the return values of the inc or shall it also contain the values which have not been given to inc? Commented May 8, 2013 at 19:51
  • sorry I should have been more specific, I just did an edit. Commented May 8, 2013 at 19:56

2 Answers 2

1
[[y if i < len(x)-2 else inc(y)
  for i, y in enumerate(x)]
  for x in my_array]
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good answer. I modified it so that r=[[y if i in (1,4) else inc(y) for i, y in enumerate(x)] for x in myarray] , this way it will be more flexiable in terms of excepting various conditions
1
l[:-2] + tuple(map(inc, l[-2:]))

4 Comments

Yeah, but I guessed that the number 2 would not be constant. Also the number of columns might be variable. I feel your answer is based on assuming too much.
Thanks for the reply. I agree with Alfe, this is somewhat hard coded.
I agree , it is more flexible
The adding needs to be done for each tuple (being an element of the array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.