#Python撲克牌的4種花色
spade = [0]*13 ; heart = [0]*13
diamond = [0]*13 ; club = [0]*13
for i in range(13):
spade[i] = “spade %d”%(i+1)
heart[i] = “hrart %d”%(i+1)
diamond[i] = “diamond %d”%(i+1)
club[i] = “club %d”%(i+1)
print(spade) ; print(heart)
print(diamond) ; print(club)
#撲克牌洗牌
#少寫了防重複邏輯
#但多寫防重複邏輯,
#發的牌又會少於52張,
#每次不一定發幾張
spade = [0]*13 ; heart = [0]*13
diamond = [0]*13 ; club = [0]*13
for i in range(13):
spade[i] = “spade %d”%(i+1)
heart[i] = “hrart %d”%(i+1)
diamond[i] = “diamond %d”%(i+1)
club[i] = “club %d”%(i+1)
a=[] ; b=[] ; c=[] ; d=[]
cards = [spade,diamond,heart,club]
#print(cards[3][12])
L=[]
import random
for r in range(4):
for c in range(13):
suit = random.randint(0,3)
pts = random.randint(0,12)
L.append(cards[suit][pts])
a = L[0:13]
b = L[13:26]
c = L[26:39]
d = L[39:52]
print(a) ; print(b) ; print(c) ; print(d)
print(len(a)) ; print(len(b))
print(len(c)) ; print(len(d))
#print(L)
#print(len(L))
#spyder輸出結果:
#第二次洗牌:
“””
a = L[0:13]
b = L[13:26]
c = L[26:39]
d = L[39:52]
把以上移出雙層迴圈之外,
也可以運作,邏輯上也好理解:
“””
“””
創出了L為長度52,元素為花色+點數的list
已經可以不重複亂數發出13張*4
使用迴圈應可以將數字替換為
L中的花色+數字
for i in range(1:53):
if i in a : a[ a.index(i) ] = L[(i-1)]
elif i in b : b[ b.index(i) ] = L[(i-1)]
elif i in c : c[ c.index(i) ] = L[(i-1)]
elif i in d : d[ d.index(i) ] = L[(i-1)]
“””
#不同方式創出長度52,
#元素為花色+點數的list
#不用多一個2D list中介
“””以下有錯誤:
File “C:\Users\USER\OneDrive\桌面\untitled0.py”, line 20, in <module>
elif cards[suit][pts] not in c:
TypeError: argument of type ‘int’ is not iterable
邏輯也有誤,第一次迴圈,創出來的第一個元素,
一定同時不在a,b,c,d,那要歸給誰?
其實錯誤在 for c in range(13)
c 跟list c重複了
但此邏輯依然不行,
a,b,c,d會發不等數目的牌
“””
spade = [0]*13 ; heart = [0]*13
diamond = [0]*13 ; club = [0]*13
for i in range(13):
spade[i] = “spade %d”%(i+1)
heart[i] = “hrart %d”%(i+1)
diamond[i] = “diamond %d”%(i+1)
club[i] = “club %d”%(i+1)
a=[] ; b=[] ; c=[] ; d=[]
cards = [spade,diamond,heart,club]
print(cards[3][12])
import random
for r in range(4):
for c in range(13):
suit = random.randint(0,3)
pts = random.randint(0,12)
if cards[suit][pts] not in a:
a.append( cards[suit][pts] )
elif cards[suit][pts] not in b:
b.append( cards[suit][pts] )
elif cards[suit][pts] not in c:
c.append( cards[suit][pts] )
elif cards[suit][pts] not in d:
d.append( cards[suit][pts] )
print(a) ; print(b) ; print(c) ; print(d)
#可以改成如下:
#輸出結果:
#最終版本:
輸出結果:
#意思一樣,但多寫了一次迴圈:
近期留言