Angular Geometry - 1 year ago 37

Python Question

I am brand new to python and coding in general. I'm actually a Cinema 4D artist. C4D has a built in python script manager. I will do my best to explain what I'm trying for.

I have a sphere. The sphere is broken up into points. I have calculated the distance each point on the sphere is away from a different object. I have made a list of all these calculated distances. I would like to make a new array of the index and the corresponding distance calculation. How do I combine the two lists into a new array? Mock example below -

`def main():`

pointdistance = [150.2, 2.3, 5.5, 145.2, 30.4, 22]

indices = list(range(len(pointdistance)))

print indices

It returns the correct number of indices needed [0,1,2,3,4,5]

my desired result would look like a combination - something like this:

`preweight = [(0,150.2)(1,2.3)(2,5.5)(3,145.2)(4,30.4)(5,22)]`

For bonus I would like to dynamically sort the new "preweight" array based on the distance calculation. So as I move the object around the array sorts from closest point to furtherest point. Kinda like this:

`postweight = [(1,2.3)(2,5.5)(5,22)(4,30.4)(3,145.2)(1,150.2)]`

Thanks in advance. I am really enjoying the help this site provides.

Answer Source

Use `enumerate(..)`

. When called on a list and iterated over, it returns elements of the list as a tuple of `(index, element)`

.

For the second half of your question, use `sorted(.., key=<func>)`

. `sorted(..)`

when called with a `key=`

will use the value returned by the function applied on the item for sorting. In your specific case, `<func>`

would be something that would take an element and return the second item of the tuple. Something like: `lambda x: x[1]`

```
>>> pointdistance = [150.2, 2.3, 5.5, 145.2, 30.4, 22]
>>> list(enumerate(pointdistance))
[(0, 150.2), (1, 2.3), (2, 5.5), (3, 145.2), (4, 30.4), (5, 22)]
>>> sorted(enumerate(pointdistance), key=lambda x: x[1])
[(1, 2.3), (2, 5.5), (5, 22), (4, 30.4), (3, 145.2), (0, 150.2)]
```