Python 使用切片语法交换列表中的元素

Python 使用切片语法交换列表中的元素,python,list,swap,slice,Python,List,Swap,Slice,我在使用以下函数时遇到了一些问题。 我想知道如何使用简单的列表方法实现文档字符串中给出的示例 # The values of the two jokers. JOKER1 = 27 JOKER2 = 28 def triple_cut(deck): '''(list of int) -> NoneType Locate JOKER1 and JOKER2 in deck and preform a triple cut.\ Everything above the firs

我在使用以下函数时遇到了一些问题。 我想知道如何使用简单的列表方法实现文档字符串中给出的示例

# The values of the two jokers.
JOKER1 = 27
JOKER2 = 28


def triple_cut(deck):
  '''(list of int) -> NoneType
  Locate JOKER1 and JOKER2 in deck and preform a triple cut.\
  Everything above the first joker goes at the bottom of the deck.\
  And everything below the second joker goes to the top of the deck.\
  Treat the deck as circular.
  >>> deck = [1, 2, 27, 3, 4, 28, 5, 6, 7]
  >>> triple_cut(deck)
  >>> deck
  [5, 6, 7, 27, 3, 4, 28, 1, 2]
  >>> deck = [28, 1, 2, 3, 27]
  >>> triple_cut(deck)
  >>> deck
  [28, 1, 2, 3, 27]
  '''
  # obtain indices of JOKER1 and JOKER2
  j1 = deck.index(JOKER1)
  j2 = deck.index(JOKER2)
  # determine what joker appears 1st and 2nd
  first = min(j1, j2)
  second = max(j1, j2)
  # use slice syntax to obtain values before JOKER1 and after JOKER2
  upper = deck[0:first]
  lower = deck[(second + 1):]
  # swap these values
  upper, lower = lower, upper
当我运行包含27和28的int.列表时,该函数不会对该列表做任何操作。
我不知道问题出在哪里,你们能帮我解决吗?

好吧,你们复制了一半的资料,更改了分配给它们的变量(如果按照你们最初想要的方式分配就更容易了)。。。就这样。你不能把他们连在一起什么的。你也没有一张中间的牌(在小丑之间)。

分配给一张牌的任务只有在你立即执行时才有效。无法保存切片,然后将其指定给它

deck[(second + 1):], deck[0:first] = deck[0:first], deck[(second + 1):]

您需要再次将这些片段粘贴在一起,如:

deck[:] = deck[second + 1:] + deck[first: second + 1] + deck[:first]

这将替换整个组(
组[:]=…
)。这很简单。试着在你自己的风险下变得更狡猾;-)

你没有从函数中返回任何东西,所以函数实际上没有做任何事情。我从这里开始。你根本没有改变
deck
——你只是重新绑定了
upper
lower