Python交换功能 [英] Python Swap Function

查看:77
本文介绍了Python交换功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用Python表达这一点.

I'm having a hard time expressing this in Python.

这是对需要完成的操作的描述.

This is the description of what needs to be done.

swap_cards:(int列表,int)-> NoneType

swap_cards: (list of int, int) -> NoneType

swap_cards([3, 2, 1, 4, 5, 6, 0], 5)
[3, 2, 1, 4, 5, 0, 6]

swap_cards([3, 2, 1, 4, 5, 6, 0], 6)
[0, 2, 1, 4, 5, 6, 3]`

我已经创建了2个示例,但是我不知道如何启动该函数的主体.

I've created 2 examples, but I don't know how to start the body of the function.

推荐答案

您可以使用元组交换惯用法a, b = b, a交换变量,请注意,在某些情况下,需要环绕索引index % len(seq)

You can use the tuple swap idiom a, b = b, ato swap the variable noting that for edge cases you need to wrap around the index index % len(seq)

实施

def swap_cards(seq, index):
    indexes = (index, (index + 1)% len(seq))
    seq[indexes[0]], seq[indexes[1]] = seq[indexes[1]], seq[indexes[0]]
    return seq

示例

>>> swap_cards([3, 2, 1, 4, 5, 6, 0], 6)
[0, 2, 1, 4, 5, 6, 3]
>>> swap_cards([3, 2, 1, 4, 5, 6, 0], 5)
[3, 2, 1, 4, 5, 0, 6]

这篇关于Python交换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆