I have been trying to code a function for a set of cards on hand, and right now the requirement is that the cards be arranged according to alphabetical order, and without the use of sorted() built-in.
I have been trying to arrange the input according to the list submatrices, so its set in stone. The Value tagged to each card is of no consequence. it can be arranged in any order as long as its all the same suite.
def suits(hand):
spades = []
diamonds = []
clubs = []
hearts = []
hList = [clubs, diamonds, hearts, spades]
for i in hand:
for j in hList:
for c in i:
c = str(c)
if str(c)=="C" and j == clubs:
hList[j].append(i)
elif str(c) =="D" and j == diamonds:
hList[j].append(i)
elif str(c) =="H" and j == hearts:
hList[j].append(i)
elif str(c) =="S" and j == spades:
hList[j].append(i)
return hList
print(suits([(4,'C'),(8,'H'),(3,'C'),(2,'D'),(8,'C')]))
[[(4,'C'),(3,'C'),(8,'C')],[(2,'D')], [(8,'H')], []]
This is the expected output, from the given input
Since the method you are asking for is just grouping them by their suits, then you can just simply go with:
def suits(hand):
hList = [[], #clubs
[], #diamonds
[], #hearts
[]] #spades
i = ['C', 'D', 'H', 'S']
for n, s in hand:
hList[i.index(s)].append((n, s))
return hList
Which will probably run as you wanted. Given your sample code:
print(suits([(4,'C'),(8,'H'),(3,'C'),(2,'D'),(8,'C')]))
It will result to:
[[(4,‘C’),(3,‘C’),(8,‘C’)],[(2,‘D’)], [(8,‘H’)], []]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.