简体   繁体   English

如何返回根据其子列表组件排列的列表

[英]How to return a list that is arranged according to its sublist components

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. 我一直在尝试为手头上的一组卡片编写函数,现在的要求是,卡片必须按照字母顺序排列,并且不使用内置的sorted()。

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 [[(4,'C'),(3,'C'),(8,'C')],[(2,'D')], [(8,'H')], []]这是给定输入的预期输出

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’)], []]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM