保留Python str中的连接元素以列出转换

时间:2012-05-18 11:28:40

标签: python string list type-conversion

我想知道是否有一个特定的方法可以让我获取一个列表元素(["3D"]),并使用for循环将其嵌套在另一个列表([["3D"]])中,同时避免当前的类型转换问题I导致[["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循环中card元素的连接性。

非常感谢。

P.S。对于那些感兴趣的人来说,它是一个纸牌游戏的游戏生成器,可以玩单张卡和2个以上的号码

1 个答案:

答案 0 :(得分: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)