python 从列表中随机选择_使用条件Python从列表中随机选择

我在一个列表中创建了一个笛卡尔积,现在我想随机取出4个不同的元组(我在文章末尾尝试过)。在shape = ['triangle' , 'square' , 'circle' , 'cross']

color = ['green' , 'red' , 'blue' , 'pink']

__cartesianPsc__ = list(itertools.product(shape , color))

我的笛卡尔积

^{pr2}$

现在我想随机得到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')

等等

有人知道怎么做吗?我试过用随机范围从三角形、正方形、圆形、十字中挑一个,但我不知道怎么做才能得到不同的颜色

----我的旧代码-----

我有一个问题,它总是(三角形,绿色)作为一个元组,但是其他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

你好,马丁:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值