在python列表中移动项目?

时间:2013-10-18 17:27:40

标签: python list indexing append

这是最终产品。如果其他人有任何提示要切断它,请告诉我!非常感谢您的帮助!

def triple_cut(deck):
    ''' (list of int) -> NoneType

    Modify deck by finding the first joker and putting all the cards above it
    to the bottom of deck, and all the cards below the second joker to the top
    of deck. 
    >>> deck = [2, 7, 3, 27, 11, 23, 28, 1, 6, 9, 13, 4]
    >>> triple_cut(deck) 
    >>> deck 
    [1, 6, 9, 13, 4, 27, 11, 23, 28, 2, 7, 3]
    '''     
    joker1 = deck.index(JOKER1)
    joker2 = deck.index(JOKER2)
    first = min(joker1, joker2)
    first_cards = []

    for cards in range(len(deck[:first])):
        cards = 0 
        pop = deck.pop(cards)
        first_cards.append(pop)

    joker1 = deck.index(JOKER1)
    joker2 = deck.index(JOKER2)
    second = max(joker1, joker2)    
    second_cards = []

    for cards in deck[second + 1:]:
        pop = deck.pop(deck.index(cards))
        second_cards.append(pop)

    second_cards.reverse()

    for card in second_cards: 
        deck.insert(0, card)

    deck.extend(first_cards)   

raah我需要输入更多内容,因为我的帖子主要是代码:请添加更多详细信息sss ss

2 个答案:

答案 0 :(得分:0)

提示:

p = list('abcdefghijkl')
pivot = p.index('g')
q = p[pivot:] + p[:pivot]

列表切片是你的朋友。

答案 1 :(得分:0)

回答第二次修订

  

当函数完成时,它不会改变套牌。

问题是你没有提供完整的代码。我猜它看起来像这样:

def triple_cut(deck)
    …
    deck = q

根据您的文档字符串,您将其称为

deck = […]
triple_cut(deck)

并且已经混淆了作业deck = q没有传播出triple_cut()。您无法修改方法的形式参数,因此赋值保持为triple_cut的本地,影响模块级变量deck

写这个的正确方法是

def triple_cut(cuttable)
    …
    return cuttable[first:] + cuttable[:first]

deck = […]
deck = triple_cut(deck)

我将参数的名称更改为cuttable以进行解释。您可以将参数名称保留为deck,但我想表明,当您认为您正在分配到套牌时,您实际上已分配给cuttable,并且该分配不会执行triple_cut()。