1

我有一个 Lego mindstorms 51515,喜欢用 python 编程。

模块中有一些默认图像我想循环使用。

import hub
images = dir(hub.Image)
print(images)

输出:

['__class__', '__name__', '__bases__', '__dict__', 'ALL_ARROWS', 'ALL_CLOCKS', 'ANGRY', 'ARROW_E', 'ARROW_N', 'ARROW_NE', 'ARROW_NW', 'ARROW_S', 'ARROW_SE', 'ARROW_SW', 'ARROW_W', 'ASLEEP', 'BUTTERFLY', 'CHESSBOARD', 'CLOCK1', 'CLOCK10', 'CLOCK11', 'CLOCK12', 'CLOCK2', 'CLOCK3', 'CLOCK4', 'CLOCK5', 'CLOCK6', 'CLOCK7', 'CLOCK8', 'CLOCK9', 'CONFUSED', 'COW', 'DIAMOND', 'DIAMOND_SMALL', 'DUCK', 'FABULOUS', 'GHOST', 'GIRAFFE', 'GO_DOWN', 'GO_LEFT', 'GO_RIGHT', 'GO_UP', 'HAPPY', 'HEART', 'HEART_SMALL', 'HOUSE', 'MEH', 'MUSIC_CROTCHET', 'MUSIC_QUAVER', 'MUSIC_QUAVERS', 'NO', 'PACMAN', 'PITCHFORK', 'RABBIT', 'ROLLERSKATE', 'SAD', 'SILLY', 'SKULL', 'SMILE', 'SNAKE', 'SQUARE', 'SQUARE_SMALL', 'STICKFIGURE', 'SURPRISED', 'SWORD', 'TARGET', 'TORTOISE', 'TRIANGLE', 'TRIANGLE_LEFT', 'TSHIRT', 'UMBRELLA', 'XMAS', 'YES', 'get_pixel', 'height', 'set_pixel', 'shift_down', 'shift_left', 'shift_right', 'shift_up', 'width']

所有只有大写字母的全名都应该是我想循环的常量。

这个怎么做?

for dynamic_image in images:
    if not dynamic_image.isupper():
        continue
    var = hub.Image.{dynamic_image} # This is the real question on how to do this
4

3 回答 3

0

使用 dict 理解来获取hub.Image仅大写的所有属性:

import hub
names = {name: getattr(hub.Image, name, None) 
         for name in dir(hub.Image) if name.isupper()}

这将给出所有常量的字典:名称及其值。例如打印它,使用

print(list(var.items())
于 2022-01-06T00:16:25.883 回答
0

您可以使用filter().isupper()

import hub
images = dir(hub.Image)
print(list(filter(lambda x: x.isupper(), names))) # Strings with uppercase letters and underscores only
print(list(filter(lambda x: x.isupper() and x.isalpha(), names))) # Strings with uppercase letters only (no underscores)
于 2022-01-06T00:18:24.917 回答
0

我解决了,答案如下:

import hub
import time

images = dir(hub.Image)
while True:
    for image in images:
        if image.upper() != image:
            continue
        print(image)
        img = hub.Image.__dict__[image]  # This was what I was looking  for
        hub.display.show(img)
        time.sleep(1)
于 2022-01-06T09:26:19.167 回答