0

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

# 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

当我运行一个 int 列表时。包含 27 和 28,该函数不对列表执行任何操作。不知道是什么问题,大家能帮帮我吗?

4

3 回答 3

1

您需要再次将这些部分粘贴在一起,例如:

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

这将替换整个卡座 ( deck[:] = ...)。这很简单。尝试变得更棘手,风险自负;-)

于 2013-11-05T01:56:45.720 回答
0

好吧,您正在复制一半的套牌,更改分配给它们的变量(首先按照您想要的方式分配它们会更容易)......就是这样。您不会将它们重新组合在一起或其他任何东西。您也没有中间部分(小丑之间的牌)。

于 2013-11-05T01:46:45.600 回答
0

仅当您立即执行时,才能分配给切片。您不能保存切片然后分配给它。

deck[(second + 1):], deck[0:first] = deck[0:first], deck[(second + 1):]
于 2013-11-05T01:48:42.803 回答