john
john

Reputation: 418

Python: replacing a variable in a looping list

I'm trying to go through a list and print out the list using a secondary list of variables.

The problem is that the variables in the list are getting assigned and set, but are not getting printed out properly. This feels like something really simple but I've been stumped for a day or so on it. Any help would be appreciated!

side = ""
sideLong = ""
sideShort = ""
sideList = ["Right", "Left"]


jointRemapList =[
    ["Char_Hips", "Root_M"],
    ["Char_" + sideLong + "Finger1", "IndexFinger1_" + sideShort],
    ["Char_" + sideLong + "Finger2", "IndexFinger2_" + sideShort]
    ]

for side in sideList:
    sideLong = side
    sideShort = side[0]

    for jointPair in jointRemapList:

        print sideLong, sideShort, jointPair

Expected output would be:

Left L ['Char_Hips', 'Root_M']
Left L ['Char_LeftFinger1', 'IndexFinger1_L']
Left L ['Char_LeftFinger2', 'IndexFinger2_L']
Right R ['Char_Hips', 'Root_M']
Right R ['Char_RightFinger1', 'IndexFinger1_R']
Right R ['Char_RightFinger2', 'IndexFinger2_R']

Upvotes: 0

Views: 279

Answers (2)

Jared Goguen
Jared Goguen

Reputation: 9010

So the issue is that you are creating the strings when jointRemapList is created, and updates to sideLong and sideShort are not going to be reflected in those strings because strings are immuatable. Try using string formatting instead.

from itertools import product

joint_remap_list = [
    ["Char_Hips", "Root_M"],
    ["Char_{side}Finger1", "IndexFinger1_{abbrev}"],
    ["Char_{side}Finger2", "IndexFinger2_{abbrev}"]
]

sides = ["Left", "Right"]

for side, pair in product(sides, joint_remap_list):
    abbrev = side[0]
    formatted = [s.format(side=side, abbrev=abbrev) for s in pair]
    print side, abbrev, formatted

Upvotes: 3

Tony
Tony

Reputation: 3058

I think the problem is happening because you are creating jointRemapList outside of your sideList loop. You want the list to be created dynamically by sideLong and sideShort, so you need to recreate it on each increment of your loop. Like the following:

side = ""
sideLong = ""
sideShort = ""
sideList = ["Right", "Left"]

for side in sideList:
    sideLong = side
    sideShort = side[0]

    jointRemapList =[
        ["Char_Hips", "Root_M"],
        ["Char_" + sideLong + "Finger1", "IndexFinger1_" + sideShort],
        ["Char_" + sideLong + "Finger2", "IndexFinger2_" + sideShort]
        ]

    for jointPair in jointRemapList:

        print sideLong, sideShort, jointPair

Upvotes: 3

Related Questions