Sorting a list of bodies by x-coordinate

Asked by Christopher Stanbridge

At one point in my code, I need to sort a list of bodies from least to greatest x-coordinate. I have attempted to use the sorted() method but am not quite sure what I would use as my "key". I know State.pos[0] stores the x-coordinate, but when I try to use
key=State.pos[0]
(or, it seems, any variant thereof) I get the following error.
TypeError: 'property' object has no attribute '__getitem__'

What would the correct sort key be here, or if there is none, what alternate methods would there be to sort particles in order of x-coordinate?

Question information

Language:
English Edit question
Status:
Solved
For:
Yade Edit question
Assignee:
No assignee Edit question
Solved by:
Jan Stránský
Solved:
Last query:
Last reply:
Revision history for this message
Best Jan Stránský (honzik) said :
#1

Hi Christopher,

"key" should be a function to be used for the sort. One possibility is to
use lambda structure [1]

key=lambda b: b.state.pos[0]

cheers
Jan

[1] https://wiki.python.org/moin/HowTo/Sorting
Dne 15.9.2014 21:08 "Christopher Stanbridge" <
<email address hidden>> napsal(a):

> New question #254558 on Yade:
> https://answers.launchpad.net/yade/+question/254558
>
> At one point in my code, I need to sort a list of bodies from least to
> greatest x-coordinate. I have attempted to use the sorted() method but am
> not quite sure what I would use as my "key". I know State.pos[0] store the
> x-coordinate, but when I try to use
> key=State.pos[0]
> (or, it seems, any variant thereof) I get the following error.
> TypeError: 'property' object has no attribute '__getitem__'
>
> --
> You received this question notification because you are a member of
> yade-users, which is an answer contact for Yade.
>
> _______________________________________________
> Mailing list: https://launchpad.net/~yade-users
> Post to : <email address hidden>
> Unsubscribe : https://launchpad.net/~yade-users
> More help : https://help.launchpad.net/ListHelp
>

Revision history for this message
Christopher Stanbridge (cws105) said :
#2

Yes, using "lambda b" indeed worked for me. Thank you kindly.

Revision history for this message
Christopher Stanbridge (cws105) said :
#3

Thanks Jan Stránský, that solved my question.