繁体   English   中英

您可以将列表的名称存储为变量,而不是列表的内容吗

[英]Can you store the name of the list as a variable, instead of the contents of the list

上下文:在 Raspberrypi 上运行的 Python 代码,用于为一些 WS2801 RGB LED 设置动画。 要设置 LED 的颜色,您需要定义 R、G 和 B 数值。 我已经设置了一些调色板来存储一系列可以很好地协同工作的 RGB 颜色,我想从这个调色板中随机选择。

我将这些调色板存储为两个列表(此处截断的列表简洁):

xmascolours = [
        (0, 137, 42),
        (243, 243, 243),
        ]

halloweencolours = [
        (21, 24, 24),
        (49, 49, 49),
        ]

然后我想从这些列表中随机选择一个。 如果我只是这样做:

colour = random.choice(xmascolours)

这工作正常。 但是为了保持我的代码清晰(因为我经常随机化这些值以使 LED 显示一系列颜色),我想将我正在使用的当前调色板存储在另一个变量中,所以我只需要更改该值一次,而不是我称之为 random.choice 的所有地方。 所以,我试图这样做:

palette = 'xmascolours'
colour = random.choice(palette)

但这似乎将颜色设置为从单词调色板中随机选择的字符! 显然我做错了什么。 有没有办法实现这一目标?

我建议使用列表字典。 这样您就可以通过调色板名称加载您需要的调色板列表。

import random
colorScheme  = {}
colorScheme["xmascolours"] = [(0, 137, 42),(243, 243, 243)]
colorScheme["halloweencolours"] = [(21, 24, 24),(21, 24, 24)]
import pprint
print("Collection of colorSchemes:")
# You do not have to use pprint it just makes the list output look nice
pprint.pprint(colorScheme)

palette = colorScheme["xmascolours"]
print("All colors from xmascolors palette:")
print(palette)
colour = random.choice(palette) 
print("Random color from palette:")
print(colour)

输出

Collection of colorSchemes:
{'xmascolours': [(0, 137, 42), (243, 243, 243)], 'halloweencolours': [(21, 24, 24), (21, 24, 24)]}
All colors from xmascolors palette:
[(0, 137, 42), (243, 243, 243)]
Random color from palette:
(0, 137, 42)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM