-4

Here is part of code. I need to understand what this code do :

if instruction == "JOINT" or instruction == "ROOT":
    parent = joint_stack[-1] if instruction == "JOINT" else None
    joint = BvhJoint(words[1], parent)
    self.joints[joint.name] = joint

How to understand this line special ->

    parent = joint_stack[-1] if instruction == "JOINT" else None

Is this code equal with JS code:

if (instruction == "JOINT") {
    parent = joint_stack[-1];
} else {

}

?

martineau
  • 119,623
  • 25
  • 170
  • 301
Nikola Lukic
  • 4,001
  • 6
  • 44
  • 75
  • Why 7 questions about similar theme was automatic flages i negative voited. Looks like a anathema. I finnaly got my script : If someone looks for bvh js loader _ https://codepen.io/zlatnaspirala/pen/mdXzeKR – Nikola Lukic Jun 15 '22 at 13:11

3 Answers3

2

The equivalent JS code would be:

   if (instruction == "JOINT") { 
        parent = joint_stack[-1];
    } else {
        parent = null;
    }

or more idiomatically:

    parent = instruction == "JOINT" ? joint_stack[-1] : null;

This ternary expression in Python:

joint_stack[-1] if instruction == "JOINT" else None

is the same as the JS ternary expression:

instruction == "JOINT" ? joint_stack[-1] : null
Samwise
  • 68,105
  • 3
  • 30
  • 44
1
 parent = joint_stack[-1] if instruction == "JOINT" else None

This will check the “instruction” is equal to “JOINT” if yes, last value of joint_stack array will be assigned to the parent, otherwise None

Januka samaranyake
  • 2,385
  • 1
  • 28
  • 50
1

The JS equivalent would be

const parent = (instruction === "JOINT")?joint_stack[-1]:null;

The shortcut to conditional expression was added to Python 2.5. See Does Python have a ternary conditional operator?

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43