【问题标题】:python list slicing and moving aroundpython列表切片和移动
【发布时间】:2016-02-16 11:33:49
【问题描述】:

我如何制作一个列表并在出现 27 或 28 时对其进行切片,当它是 27 时,它之后的所有数字都会排到顶部,而 28 之前的任何数字都会排到底部。以前我只有一些涉及交换它的功能,但我不确定它是否有助于此功能。

>>> list = [1,2,3,28,4,5,6,27,7,8,9]
>>> list = [7,8,9,28, 4,5,6,27,1,2,3]


def triple_cut(cards):
    if 27 and 28 in cards:
        return cards[(index(27)):end] + cards[(index(28)):(index(27))] + cards[:(index(28))]

逻辑应该是这样的,但由于某种原因我不能做索引,谁能帮助修复我的代码,这样它就可以工作了

【问题讨论】:

    标签: python list slice


    【解决方案1】:

    使用cards.index(27)cards.index(28)

    【讨论】:

    • return cards[cards.index(27)+1:] + cards[cards.index(28):cards.index(27)+1] + cards[:cards.index(28)]
    • 我试过了,但显然它给了我 [27, 7, 8, 9, 28, 4, 5, 6, 1, 2, 3] 而我想要的([7,8,9 ,28, 4,5,6,27,1,2,3])
    • 所以你几乎得到了很好的结果——你只需要在某些地方添加+1。请参阅我之前的评论。
    • 如果我想在我已经有了 move_27 和 move_28 之后更改代码,它将 27 与下一个数字交换,将 28 与下一个 2 数字交换,这应该看起来像卡片 = ([7,8, 9,4,5,28,6,1,27,2,3])
    • 新问题 = 在 stackoverflow 上创建新问题。
    猜你喜欢
    • 2014-11-02
    • 2010-12-14
    • 2017-06-24
    • 2015-02-19
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多