代码之家  ›  专栏  ›  技术社区  ›  notacorn

我试图用函数修改列表中的值,但失败了[重复]

  •  0
  • notacorn  · 技术社区  · 8 年前
    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']
    

    如您所见,在deckStrength函数中有最后一个for循环,我试图去掉我的甲板列表中每个字符串中的最后一个字符。这件事没有发生,有什么线索说明原因吗?

    我还想补充一下,我尝试在不使用deck作为函数参数的情况下执行此操作,并调用“global deck”,但这不起作用,所以我尝试了此操作。

    1 回复  |  直到 8 年前
        1
  •  1
  •   chevybow    8 年前

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

    例如:

    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)