所以,我要制作一张异常的纸牌。每张卡片都有一个颜色(红色,绿色,蓝色),一个度数(1,2,3),一个符号(三角形,正方形,圆形)和一个数字。(1,2,3)我有一个看起来像的类像这样。
class card:
def __init__(self, color, degree, symbol, number):
self.color=color
self.degree=degree
self.symbol=symbol
self.number=number
def __repr__(self):
return "(%s,%s,%s,%s)" %(self.color,self.degree,self.symbol,self.number)
我也有这些列表,其中包含所有变量以及需要卡片的一副卡片。
colors=["red", "green", "blue"]
degrees=["1","2","3"]
symbols=["triangle", "square", "circle"]
numbers=["1","2","3"]
deck=[]
现在,我想做的是用所有可能的卡创建一个完整的卡组。优选地,它们将处于随机顺序,但是不是必需的。 我知道,如果只是数字和颜色,我就可以轻松地做到这一点。
deck = [card(value, color) for value in range(0, 2) for color in colors]
但是,当我也要使用符号和度数时,我不知道该怎么做。我试图建立更多的if语句来循环所有这些,但是那没有用。我也不希望同一张卡片出现两次,并且我也不想一张不遵循班级规则的卡片,因此必须将其结构化为[颜色,度,符号,数字]
有人知道该去哪里吗?
答案 0 :(得分:2)
带有所有可能的卡组合的全副牌:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="product" id="product_1">
<b>product1</b>
<p class="details">details</p>
</div>
<div class="product" id="product_2">
<b>product2</b>
<p class="details">details</p>
</div>
<div class="product" id="product_3">
<b>product3</b>
<p class="details">details</p>
</div>
<script>
$(function(){
$('.product').on('click',function(e){
$('.details').hide();
$(this).find('.details').show();
});
});
</script>
要随机抽取卡片组中的卡顺序,请查看以下内容:Shuffling a list of objects
答案 1 :(得分:1)
使用product
中的itertools
import itertools
deck = [
card(color, degree, symbol, number)
for color, degree, symbol, number in
itertools.product(colors, degrees, symbols, numbers)
]
答案 2 :(得分:0)
您是否想要颜色,度数,符号和数字的所有组合?
如果是这样,请使用嵌套的for循环:
deck = []
for color in colors:
for degree in degrees:
for symbol in symbols:
for number in numbers:
deck.append(card(color, degree, symbol, number)
# Also written as a list comprehension
deck = [
card(color, degree, symbol, number)
for color in colors
for degree in degrees
for symbol in symbols
for number in numbers
] # The indent is just to show how it works. For style, put them all at the same indent.
或使用itertools.product
(也可以是懒惰的)
deck = itertools.starmap(card, itertools.product(colors, degrees, symbols, numbers))
deck = list(deck) # If you really need it to be a list
答案 3 :(得分:0)
import itertools
identifiers = [colors, degrees, symbols, numbers]
deck = [[*i] for i in itertools.product(*identifiers)]
[['red', '1', 'triangle', '1'], ['red', '1', 'triangle', '2'], ['red', '1', 'triangle', '3'],...