0

我想知道是否有一种特殊的方法可以让我获取一个列表元素 ( ["3D"]),并使用 for 循环将其嵌套在另一个列表 ( [["3D"]]) 中,同时避免我遇到的当前类型转换问题导致[["3","D"]].

为了清楚起见,我包括了以下内容;

hand = ["3D", "4D", "4C", "5D", "JS", "JC"]

from itertools import groupby 

def generate_plays(hand):
    plays = []
    for rank,suit in groupby(hand, lambda f: f[0]):
        plays.append(list(suit))
    for card in hand:
        if card not in plays:       #redundant due to list nesting
            plays.append(list(card))       #problematic code in question
    return plays

输出:

[['3D'], ['4D', '4C'], ['5D'], ['JS', 'JC'], ['3', 'D'], ['4', 'D'], ['4', 'C'], ['5', 'D'], ['J', 'S'], ['J', 'C']]

预期输出:

[['3D'], ['4D', '4C'], ['5D'], ['JS', 'JC'], ['4D'], ['4C'], ['5D'], ['JS'], ['JC']]

重申一下,这里的目的是在 for 循环中保留卡片元素的连接性。

非常感谢。

PS 对于那些有兴趣的人,它是一个纸牌游戏的游戏生成器,可以玩单张牌和 2 个以上的数字

4

1 回答 1

2
hand = ["3D", "4D", "4C", "5D", "JS", "JC"]

from itertools import groupby 

def generate_plays(hand):
    plays = []
    for rank,suit in groupby(hand, lambda f: f[0]):
        plays.append(list(suit))
    for card in hand:
        if [card] not in plays:       #redundant due to list nesting
            plays.append([card])       #problematic code in question
    return plays

print generate_plays(hand)
于 2012-05-18T11:35:00.600 回答