Python交换函数
我很难用Python来表达这一点 这是对需要做什么的描述 交换卡:(整数列表,整数)->非类型Python交换函数,python,list,swap,Python,List,Swap,我很难用Python来表达这一点 这是对需要做什么的描述 交换卡:(整数列表,整数)->非类型 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]` 我创建了两个示例,但我不知道如何启动函数体。听起来这里需要一些索引符号: >>> def swap_cards(L, n): ... i
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]`
我创建了两个示例,但我不知道如何启动函数体。听起来这里需要一些索引符号:
>>> def swap_cards(L, n):
... if len(L) == n + 1:
... L[n], L[0] = L[0], L[n]
... return L
... L[n], L[n+1] = L[n+1], L[n]
... return L
...
>>> 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]
您可以使用元组交换习惯用法
a,b=b,a
来交换变量,注意对于边缘情况,您需要围绕索引索引%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]
输出:
[0, 2, 1, 4, 5, 6, 3]
如果它是非类型函数,是否允许在主体中写入“return”?(对不起,我是新程序员)@sarah我不知道你说的“非类型”函数是什么意思。
[0, 2, 1, 4, 5, 6, 3]