1

I have an array of objects where each object has a search_order attribute. I was to go over the array and increase that attribute by 1 for all objects This is the easy way:

res = []
for r in array:
    r.search_order+=1
    res.append(r)
return iter(res) 

Is there a one line for loop that can accomplish this?

return (r.search_order+=1 for r in array)

Doest seem to work unfortunately.

0

2 Answers 2

1

This may not be one line but this does the job correctly

def incr_search_order(x):
    x.search_order += 1
    return x

retrun map(incr_search_order, array)
<or>
return [incr_search_order(x) for x in array]
Sign up to request clarification or add additional context in comments.

Comments

0

You can not use an assignment within generator expression or list comprehension (it will raise SyntaxError).

Instead add the attribute with 1 and reassign the result :

old_array=(r.search_order+1 for r in array)

Comments

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.