我想创建一个字典,将三组的所有组合映射为一个整数。是否可以在单行和不使用任何导入的情况下执行此操作?
使用itertools可以通过以下方式完成:
colours = ['red','green','blue']
shapes = ['circle','square','triangle']
sizes = ['small','medium','large']
import itertools as it
lookup = {key:val for val,key in enumerate(it.product(colours,shapes,sizes))}
但是,我无法弄清楚如何使用嵌套的for循环和列表理解进行枚举。例如,下面的语法是一种尝试,但是不会在for循环的每个级别上递增:
lookup = {(c,s,z):i for i,c in enumerate(colours) for s in shapes for z in sizes}
输出应如下所示:
{('red', 'circle', 'small'): 0,
('red', 'circle', 'medium'): 1,
('red', 'circle', 'large'): 2,
('red', 'square', 'small'): 3,
('red', 'square', 'medium'): 4,
...
答案 0 :(得分:4)
您可以像这样枚举内部迭代器:
>>> {x: i for i, x in enumerate(((c, s, z) for c in colours for s in shapes for z in sizes))}
{('red', 'circle', 'small'): 0,
('red', 'circle', 'medium'): 1,
('red', 'circle', 'large'): 2,
('red', 'square', 'small'): 3,
('red', 'square', 'medium'): 4,
('red', 'square', 'large'): 5,
('red', 'triangle', 'small'): 6,
('red', 'triangle', 'medium'): 7,
('red', 'triangle', 'large'): 8,
('green', 'circle', 'small'): 9,
('green', 'circle', 'medium'): 10,
('green', 'circle', 'large'): 11,
('green', 'square', 'small'): 12,
('green', 'square', 'medium'): 13,
('green', 'square', 'large'): 14,
('green', 'triangle', 'small'): 15,
('green', 'triangle', 'medium'): 16,
('green', 'triangle', 'large'): 17,
('blue', 'circle', 'small'): 18,
('blue', 'circle', 'medium'): 19,
('blue', 'circle', 'large'): 20,
('blue', 'square', 'small'): 21,
('blue', 'square', 'medium'): 22,
('blue', 'square', 'large'): 23,
('blue', 'triangle', 'small'): 24,
('blue', 'triangle', 'medium'): 25,
('blue', 'triangle', 'large'): 26}
使代码更具可读性:
{
obj: index for index, obj in enumerate(
(
(color, shape, size) for color in colours
for shape in shapes
for size in sizes
)
)
}
答案 1 :(得分:1)
您可以尝试:
lookup = {(c,s,z): i+3*j+9*k for i,c in enumerate(colours) for j,s in enumerate(shapes) for k,z in enumerate(sizes)}
输出:
{
('red', 'circle', 'small'): 0,
('red', 'circle', 'medium'): 9,
('red', 'circle', 'large'): 18,
('red', 'square', 'small'): 3,
('red', 'square', 'medium'): 12,
('red', 'square', 'large'): 21,
('red', 'triangle', 'small'): 6,
('red', 'triangle', 'medium'): 15,
('red', 'triangle', 'large'): 24,
('green', 'circle', 'small'): 1,
('green', 'circle', 'medium'): 10,
('green', 'circle', 'large'): 19,
('green', 'square', 'small'): 4,
('green', 'square', 'medium'): 13,
('green', 'square', 'large'): 22,
('green', 'triangle', 'small'): 7,
('green', 'triangle', 'medium'): 16,
('green', 'triangle', 'large'): 25,
('blue', 'circle', 'small'): 2,
('blue', 'circle', 'medium'): 11,
('blue', 'circle', 'large'): 20,
('blue', 'square', 'small'): 5,
('blue', 'square', 'medium'): 14,
('blue', 'square', 'large'): 23,
('blue', 'triangle', 'small'): 8,
('blue', 'triangle', 'medium'): 17,
('blue', 'triangle', 'large'): 26
}
然后为了按值对字典进行排序:
lookup=dict(sorted(lookup.items(), key=lambda x: x[1] ))