0

好的,这里有一些背景信息:

我的纸牌游戏有 4 个玩家,每个玩家都有一手牌。pHands 是其他 4 个玩家手牌的列表(pHands 中还有 4 个其他列表)

列表在 pHands(玩家手中)中看起来像这样:['as', '2s', '4h', .... , 'ad']

列表中每个元素的第一个字符是卡片,列表中每个元素的第二个字符是套件。

我想在列表的每个元素中取出西装,所以我有以下功能:

def slicing(player):

    slicing_p1(player)
    slicing_p2(player)

def slicing_p1(player):

    pHandsSlice = pHands[player]
    pHandsString = ", ".join(pHands[player])
    x = len(pHands[player])
    for i in range(x):
        y = ''.join(pHandsSlice[i])
        y = y.replace(y[1], "")
        global myStrList
        global myStr
        myStrList = myStrList + y
        myStr = myStr + y + ","

def slicing_p2(player):

    x = len(myStr)
    global myStr
    global myStrList
    myStr = myStr[:-1]
    myStrList = list(myStrList)

然后我执行这些功能:

slicing(0)
slicing(1) <------- this is where the error occurs. 

错误:

 File "C:\Users\xxx\Downloads\UPDATE Assignment 2 (of 2)\GoFishPack\GoFishGameEngineSkeleton.py", line 63, in slicing
slicing_p1(player)
 File "C:\Users\xxx\Downloads\UPDATE Assignment 2 (of 2)\GoFishPack\GoFishGameEngineSkeleton.py", line 75, in slicing_p1
myStrList = myStrList + y

TypeError:只能将列表(不是“str”)连接到列表

这是怎么回事,我该如何解决?

4

3 回答 3

0

问题是当你做类似 + 的事情时,python 期望这是一个列表。这是一个例子。

>>> [1, 2, 30] + [1, 3]
[1, 2, 30, 1, 3]

这个过程称为串联。由于您只能连接两个列表,因此当您尝试将列表与非列表连接时会收到错误。y在你的情况下是一个str。您要做的是追加y到您的列表中,myStrList. 您可以通过在myStrList.

>>> myStrList = [1, 2, 4]
>>> y = 'a'
>>> myStrList.append(y)
[1, 2, 4, 'a']
于 2013-07-25T04:38:53.077 回答
0

如果您只想获得每张牌的花色,那么只需执行以下操作:

for playerhand in pHands:
    for card in playerhand:
        print card[1]

如果您想获得特定玩家手中所有牌的花色,请执行以下操作:

def suits(player):
    for card in pHands[player]:
        print card[1]

例如,您可以suits(1)打印玩家 1 手中每张牌的花色。

如果您想从每张牌中删除花色(即,每个玩家只剩下一个数字列表),那么:

def remove_suits():
    newhands = [] # temporary variable that will replace pHands
    for playerhand in pHands: # for each hand
        newhand = [] # temporary variable for what their new hand will be
        for card in playerhand:
            newcard = card[0] # make the card equal to only the first character in the hand, in this case, the number
            newhand.append(newcard) # store this card to the temporary variable
        newhands.append(newhand) # push this hand to the temporary variable for the new set of hands
    global pHands # if you're working with globals
    pHands = newhands # now change pHands to be equal to your new list
于 2013-07-25T04:39:32.210 回答
0

这是因为你试图连接一个列表和一个 str

说你是玩家手牌['as','2s','4d','4h'],这意味着 for 循环将输出

a
2
4
4

如果你这样做type(y)了,<type "str">它们就是字符串

然后你尝试在这一行添加字符串列表:

myStrList = myStrList + y

您需要使用append()将字符串转换为列表的新项目

所以在 th for 循环的每次迭代中,您需要执行以下操作:

myStrList.append(y)
于 2013-07-25T04:46:22.007 回答