Python - How to make a 2D array, or an array of arrays?

Python - How to make a 2D array, or an array of arrays?

dkrelina
Advocate Advocate
2,360 Views
3 Replies
Message 1 of 4

Python - How to make a 2D array, or an array of arrays?

dkrelina
Advocate
Advocate

I have a scene with a number of group nodes. Each group node contains a unique number of individual meshes.


I would like to create a python script that takes the selected groups, creates a joint for each of the meshes inside the group, and appends the newly created joint to an array.


Let's say...
myJoints is the name of the joint array
and...
group1 contains 6 meshes
group2 contains 13 meshes
group3 contains 8 meshes

 

How would I go about appending the newly created joints to the array? Is there such a thing as a 2D array? Or an array of arrays?


Normally I might use something like:
myJoints.append(newJoint)


However, in this case I would want to have an array that holds multiple arrays, so I'd be inclined to do something like this, but it doesn't seem to work:
myJoints[i].append(newJoint)

0 Likes
Accepted solutions (1)
2,361 Views
3 Replies
Replies (3)
Message 2 of 4

RFlannery1
Collaborator
Collaborator
Accepted solution

The last line of code you posted should work.  Without seeing the rest of your code, I can't be sure, but I suspect that you just need to initialize a blank list for each group before adding to it.  For example, the following code will give an error:

myJoints = []
for i, group in enumerate(selectedGroups): for mesh in group:
newJoint = makeNewJoint()
myJoints[i].append(newJoint)

But the error can be fixed:

myJoints = []
for group in selectedGroups:
jointGroup = [] for mesh in group: newJoint = makeNewJoint() jointGroup.append(newJoint)
myJoints.append(jointGroup)

As a separate note, I would recommend storing the data in a dict rather than in a list of lists.  That way you can refer to each group by name instead of having to remember "groupA is index 0, groupB is index 1, etc.".  Something like the following:

myJoints = {}
for group in selectedGroups:
    myJoints[group] = []
for mesh in group:
newJoint = makeNewJoint()
myJoints[group].append(newJoint)
Message 3 of 4

dkrelina
Advocate
Advocate

Thank you @RFlannery1! That worked well. In my case, the list of lists route did the trick since I don't need to refer to each group by name.

 

How do I query or edit an individual joint in this list of lists? Can I use the name of the array followed by two sets of square brackets? ex. myJoints[i][j] ?

 

Will this work?

 

# set translateX of joint 2 in group 0
cmds.setAttr(myJoints[0][2] + '.translateX', 20 )
0 Likes
Message 4 of 4

RFlannery1
Collaborator
Collaborator

Yes, that works.