【发布时间】:2016-02-16 06:10:59
【问题描述】:
我在列表中创建了一个笛卡尔积,现在我想随机取出 4 个不同的元组(我在帖子末尾尝试)。
shape = ['triangle' , 'square' , 'circle' , 'cross']
color = ['green' , 'red' , 'blue' , 'pink']
__cartesianPsc__ = list(itertools.product(shape , color))
我的笛卡尔积
[('triangle', 'green'), ('triangle', 'red'), ('triangle', 'blue'), ('triangle', 'pink'), ('square', 'green'), ('square', 'red'), ('square', 'blue'), ('square', 'pink'), ('circle', 'green'), ('circle', 'red'), ('circle', 'blue'), ('circle', 'pink'), ('cross', 'green'), ('cross', 'red'), ('cross', 'blue'), ('cross', 'pink')]
现在我想用三角形、正方形、圆形和十字形和 4 种不同颜色的绿色、红色、粉色、蓝色随机获得 4 个不同的元组,但每种颜色和每种形状/颜色只存在一次 示例:
第一选择
first = ('triangle', 'green')
second = ('square', 'red')
third = ('circle', 'blue')
fourth = ('cross', 'pink')
第二
first = ('circle', 'blue')
second = ('cross', 'red')
third = ('triangle', 'pink')
fourth = ('square', 'green')
等
有人知道怎么做吗?我尝试了一个带有 random.range 的 While-Loop 从三角形、正方形、圆形、十字形中选择一个,但我不知道如何获得不同的颜色
--------我的旧代码----- 我有一个问题,它总是有(三角形,绿色)作为一个元组,但其他 3 个元组是不同的(每次)。
shape = ['triangle' , 'square' , 'circle' , 'cross']
color = ['green' , 'red' , 'blue' , 'pink']
__cartesianPsc__ = list(itertools.product(shape , color))
while True:
se1 = random.randrange(0, 4, 1)
se2 = random.randrange(5, 8, 1)
se3 = random.randrange(9, 12, 1)
se4 = random.randrange(13, 16, 1)
# safe the randomly choosen tuple of the cartesian product
first = __cartesianPsc__[se1] #triangle X color
second = __cartesianPsc__[se2] # square X color
third = __cartesianPsc__[se3] #circle X color
fourth = __cartesianPsc__[se4] #cross X color
# if statement to stop the While-LOOP only if there are 4 tuples with
# 4 different shapes and colors !
"""Problem: (triangle, green) is always a tuple, no other color with triangle
if second[1] != first[1] and second[1] != third[1] and second[1] != fourth[1] \
and third[1] != first[1] and third[1] != second[1] and third[1] != fourth[1] \
and fourth[1] != first[1] and fourth[1] != second[1] and fourth[1] != third[1] \
and first[1] != second[1] and first[1] != third[1] and first[1] != fourth[1]:
"""
break
问候马丁 :)
【问题讨论】:
-
不要先创建笛卡尔积。只需单独调整形状和颜色并
zip它们。 -
您对
__cartesianPsc__使用双下划线有什么原因吗?通常这样的下划线用于表示魔法对象。 PEP8 说:“永远不要发明这样的名字;只使用它们作为记录”
标签: python list random cartesian-product