【问题标题】:swapping function交换功能
【发布时间】:2015-11-15 00:42:10
【问题描述】:

现在我有一个函数可以将列表中的位置与下一个数字交换其索引,例如swap_cards([1,2,3,4,5], 2) -> swap_cards = [1,2,4,3,5] 如何更改我的代码,以便当我在另一个函数中调用它时,我可以更改函数 swap_cards 的索引

def swap_cards(cards, index):
    cards_len = len(cards)
    if not 0 <= index < cards_len:
        return cards
    elif index == cards_len - 1:
        return [cards[-1]] + cards[1:-1] + [cards[0]]
    else:
        return cards[:index] + [cards[index+1]] + [cards[index]] +\
            cards[index+2:]

def move_3(cards):
    if 3 in cards:
        swap_cards(cards, cards.index(3))
        return cards

目前我只能找到索引的位置,但不确定如何将索引再移动一个空间

【问题讨论】:

  • “更改我的代码,以便在另一个函数中调用它时我可以更改函数 swap_cards 的索引”是什么意思?

标签: python list python-3.x swap


【解决方案1】:

我认为这就是您说要更改索引时的意思。

def swap_cards(cards, index):
    cards_len = len(cards)
    if not 0 <= index < cards_len:
        return cards
    elif index == cards_len - 1:
        return [cards[-1]] + cards[1:-1] + [cards[0]]
    else:
        return cards[:index] + [cards[index+1]] + [cards[index]] +\
            cards[index+2:]

更新功能。

def move_3(cards):
    for item in cards:
        if item == 3:
           return swap_cards(cards, index=3)

如果您在此函数中输入相同的数字列表 [1,2,3,4,5],您将得到 [1, 2, 3, 5, 4]。

print(move_3([1,2,3,4,5]))
[1, 2, 3, 5, 4]

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 2012-04-14
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多