如何用for循环/列表推导式从任意元组生成电机控制元组?
Let's break this down into two key parts: automating the generation of combined motor tuples (like TRACKS[0] and ARM[0]) and building a flexible motorcmb function that works with any number of motors.
1. Automate Combined Tuple Generation
Instead of manually writing bitwise ORs for every combination, we can use functools.reduce to iterate through target motors and combine their forward/reverse configurations automatically. This keeps your code clean and easy to update if motor groups change later.
First, define a helper function to generate the combined forward/reverse pair for a list of motor IDs:
from functools import reduce def combine_motors(motor_ids, motor_config): # Combine all forward direction masks forward = reduce( lambda a, b: (a[0] | b[0], a[1] | b[1], a[2] | b[2]), [motor_config[mid][0] for mid in motor_ids] ) # Combine all reverse direction masks reverse = reduce( lambda a, b: (a[0] | b[0], a[1] | b[1], a[2] | b[2]), [motor_config[mid][1] for mid in motor_ids] ) return (forward, reverse)
Now rewrite TRACKS and ARM using this helper—no manual bitwise ORs needed:
# TRACKS:双侧、左侧、右侧(前进、后退) TRACKS = ( combine_motors([4, 5], MOTORS), # Auto-combine m4 and m5 MOTORS[4], MOTORS[5] ) # ARM:全部、肘部、腕部、夹爪(前进/张开、后退/闭合) ARM = ( combine_motors([1, 2, 3], MOTORS), # Auto-combine m1, m2, m3 MOTORS[1], MOTORS[2], MOTORS[3] )
If you want to generate the entire structure dynamically (including individual motors), use list comprehensions to unpack items:
# Example: Generate full ARM structure dynamically arm_motor_ids = [1, 2, 3] ARM = ( combine_motors(arm_motor_ids, MOTORS), *[MOTORS[mid] for mid in arm_motor_ids] # Unpack individual motor configs )
2. Generic motorcmb Function for Any Number of Motors
The original motorcmb only handles 2 motors, but we can use variable arguments (*args) to accept any number of (motor_id, motor_dir) pairs, then combine them with reduce:
def motorcmb(*motor_pairs, motor_config): # Handle empty input case gracefully if not motor_pairs: return (0, 0, 0) # Iteratively OR all motor configuration tuples return reduce( lambda a, b: (a[0] | b[0], a[1] | b[1], a[2] | b[2]), [motor_config[mid][dir] for mid, dir in motor_pairs] )
Usage Examples
# Combine m1 forward and m3 reverse mask1 = motorcmb((1, 0), (3, 1), motor_config=MOTORS) # Combine m4 forward, m5 reverse, and m2 forward mask2 = motorcmb((4, 0), (5, 1), (2, 0), motor_config=MOTORS)
Key Best Practices
- DRY Code: The helper functions eliminate repetitive manual bitwise operations, making it easier to adjust motor groups later (e.g., add a new motor to the ARM without rewriting ORs).
- Scalability: Using
reduceensures the solution works for any number of motors, not just fixed groups of 2 or 3. - Edge Case Handling: The guard clause in
motorcmbprevents errors when no motors are passed, returning a safe zero mask instead.
内容的提问来源于stack exchange,提问作者zimchaa

