使用for/list comprehension从任意数量的其他元组创建元组

2024-10-03 00:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我正在研究如何创建TRACKS[0]ARM[0]元组(甚至是一个完整的集合,例如ARM),因为它们非常相似-我认为类似于列表理解的东西可以工作(因为我正在为每个循环绘制一个示例)。你知道吗

# MOTORS: all, m1, m2, m3, m4, m5 (+, -)
MOTORS = (
  (
    (0b01010101, 0b00000001, 0b00000000),
    (0b10101010, 0b00000010, 0b00000000)
  ),
  (
    (2**0, 0, 0),
    (2**1, 0, 0)
  ),
  (
    (2**2, 0, 0),
    (2**3, 0, 0)
  ),
  (
    (2**4, 0, 0),
    (2**5, 0, 0)
  ),
  (
    (2**6, 0, 0),
    (2**7, 0, 0)
  ),
  (
    (0, 2**0, 0),
    (0, 2**1, 0)
  )
)

LED = (0,0,1)

# TRACKS: both, left, right (forward, reverse) 
TRACKS = (
    (
      (MOTORS[4][0][0] | MOTORS[5][0][0], MOTORS[4][0][1] | MOTORS[5][0][1], MOTORS[4][0][2] | MOTORS[5][0][2]),
      (MOTORS[4][1][0] | MOTORS[5][1][0], MOTORS[4][1][1] | MOTORS[5][1][1], MOTORS[4][1][2] | MOTORS[5][1][2])
    ),
    MOTORS[4],
    MOTORS[5]
  )

# ARM: all, elbow, wrist, grip (forward/open, reverse/close)  
ARM = (
  (
      (MOTORS[1][0][0] | MOTORS[2][0][0] | MOTORS[3][0][0], MOTORS[1][0][1] | MOTORS[2][0][1] | MOTORS[3][0][1], MOTORS[1][0][2] | MOTORS[2][0][2] | MOTORS[3][0][2]),
      (MOTORS[1][1][0] | MOTORS[2][1][0] | MOTORS[3][1][0], MOTORS[1][1][1] | MOTORS[2][1][1] | MOTORS[3][1][1], MOTORS[1][1][2] | MOTORS[2][1][2] | MOTORS[3][1][2])
    ),
    MOTORS[1],
    MOTORS[2],
    MOTORS[3]
  )

def motormsk (motor_id, motor_config):
  return (motor_config[motor_id][0][0] | motor_config[motor_id][1][0], motor_config[motor_id][0][1] | motor_config[motor_id][1][1], motor_config[motor_id][0][2] | motor_config[motor_id][1][2])

motormsk函数执行一个逻辑OR来创建传入值的掩码,我认为可以递归地使用它来生成掩码,该函数需要接受任意数量的元组。你知道吗

此配置用于与USB电机控制接口(如OWI-535机械臂边缘)连接,我正在添加虚拟系统配置(ARMTRACKS),以允许我轻松地更改它们/重新使用它们。你知道吗

用法:发送MOTORS[0][0]启动所有电机向前,TRACKS[0][1]启动磁道反向,TRACKS[1][0]启动左磁道向前,motormsk(3, ARM)停止夹持电机,等等

有一个复制这里:https://repl.it/@zimchaa/robo-config-谢谢。你知道吗

编辑:有了改写的建议和对问题的澄清,我已经尝试了两个要素的问题:

def motorcmb (motor_id_1, motor_dir_1, motor_id_2, motor_dir_2, motor_config):
  return (motor_config[motor_id_1][motor_dir_1][0] | motor_config[motor_id_2][motor_dir_2][0], motor_config[motor_id_1][motor_dir_1][1] | motor_config[motor_id_2][motor_dir_2][1], motor_config[motor_id_1][motor_dir_1][2] | motor_config[motor_id_2][motor_dir_2][2])

这会产生:motorcmb(1, 0, 2, 1, TRACKS)

=> (64, 2, 0)

我仍然想看看对于任意数量的元素有什么可能/最佳实践。你知道吗


Tags: idconfigreturndefdirallarm电机
1条回答
网友
1楼 · 发布于 2024-10-03 00:26:01

我建议使用itertools.chain()将可变的元组数减少为一个序列,然后

from operator import __or__
from functools import reduce 
x = reduce(__or__, myiterable)

把它们放在一起。我真的不明白你的元组是如何嵌套的,所以我不打算尝试和进入细节。你知道吗

相关问题 更多 >