[英]How to return a list that is arranged according to its sublist components
我一直在嘗試為手頭上的一組卡片編寫函數,現在的要求是,卡片必須按照字母順序排列,並且不使用內置的sorted()。
我一直在嘗試根據列表子矩陣來安排輸入,因此將其固定在一塊。 標記到每張卡上的價值無關緊要。 只要所有套件都相同,它就可以按任何順序排列。
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')], []]
這是給定輸入的預期輸出
由於您所要求的方法只是按照他們的西裝進行分組,因此您可以簡單地選擇:
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
這可能會按您的意願運行。 給定您的示例代碼:
print(suits([(4,'C'),(8,'H'),(3,'C'),(2,'D'),(8,'C')]))
結果將是:
[[(4,‘C’),(3,‘C’),(8,‘C’)],[(2,‘D’)], [(8,‘H’)], []]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.