我试图用函数修改列表中的值,但失败

时间:2018-08-03 18:19:47

标签: python python-3.x for-loop

deck = ['1c', '4s', '8s', '8h', '1h', '2s', '2c', '8h', 'ks', 'qd', '4d', 'jd', '7c', '10h', '5c', '10d', '3d', '9c', '7d', '4h', '2s']
powerCard = "1c"
def deckStrength(powerCard, deck):
#     global deck
    powerCardExists = False
    for card in deck:
        if card == powerCard:
            powerCardExists = True
    if(powerCardExists):
        deck.remove(powerCard)
    for card in deck:
        card = card[:-1]
    print(deck)

deckStrength(powerCard, deck)

如果运行此命令,输出将是:

['4s', '8s', '8h', '1h', '2s', '2c', '8h', 'ks', 'qd', '4d', 'jd', '7c', '10h', '5c', '10d', '3d', '9c', '7d', '4h', '2s']

如您所见,在我的eckStrength函数中使用了最后一个for循环时,我试图摆脱我的卡片组列表中每个字符串中的最后一个字符。这没有蒸腾,为什么有任何线索?

我还想补充一点,我尝试在不使用甲板的情况下将其作为函数的参数并调用“全局甲板”,但这没有用,所以我尝试了此。

1 个答案:

答案 0 :(得分:1)

您需要创建一个新列表并将该列表分配给您的更改

例如:

deck = ['1c', '4s', '8s', '8h', '1h', '2s', '2c', '8h', 'ks', 'qd', '4d', 'jd', '7c', '10h', '5c', '10d', '3d', '9c', '7d', '4h', '2s']
powerCard = "1c"
def deckStrength(powerCard, deck):
#     global deck
    powerCardExists = False
    for card in deck:
        if card == powerCard:
            powerCardExists = True
    if(powerCardExists):
        deck.remove(powerCard)
    new_deck = [card[:-1] for card in deck]
    print(new_deck)

deckStrength(powerCard, deck)