Python:替换循环列表中的变量

时间:2017-06-14 17:16:20

标签: python list loops

我正在尝试浏览列表并使用辅助变量列表打印出列表。

问题是列表中的变量正在分配和设置,但是没有正确打印出来。这感觉就像一件非常简单的东西,但我已经被困了一天左右。任何帮助将不胜感激!

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

预期输出为:

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']

2 个答案:

答案 0 :(得分:3)

我认为问题正在发生,因为您在jointRemapList循环之外创建了sideList。您希望列表由sideLongsideShort动态创建,因此您需要在循环的每个增量上重新创建它。如下所示:

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

答案 1 :(得分:3)

所以问题是你在创建sideLong时创建字符串,而sideShortfrom 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 的更新不会反映在这些字符串中,因为字符串是不可移动的。请尝试使用字符串格式。

foo_sym