列表中的Python索引更改
# write a function that accepts a list and the indexes of two elements in the list,
# and swaps that two elements of the list, and return the swapped list.
# for example, if the arguments of the function are [23,65,19,90]m index1 = 1, and index2 = 3,
# then it will return [23,90,19,65].
# Swap function
def swapLst(newLst):
size = len(newLst)
# Swapping
temp = newLst[0]
newLst[0] = newLst[size - 1]
newLst[size - 1] = temp
return newLst
newLst = [23,65,19,90]
print(swapLst(newLst))
您好,我的问题:如何更改代码以更改列表中的任何索引。我的程序只会更改和最后一个索引,我需要帮助。谢谢你!
# write a function that accepts a list and the indexes of two elements in the list,
# and swaps that two elements of the list, and return the swapped list.
# for example, if the arguments of the function are [23,65,19,90]m index1 = 1, and index2 = 3,
# then it will return [23,90,19,65].
# Swap function
def swapLst(newLst):
size = len(newLst)
# Swapping
temp = newLst[0]
newLst[0] = newLst[size - 1]
newLst[size - 1] = temp
return newLst
newLst = [23,65,19,90]
print(swapLst(newLst))
Hello, My question: How can I change my code to change the any index in the list. My program only changes first and last index, I needed help with that. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
a,b = b,a
在python中交换变量,因此您可以将列表元素与其索引交换:输出:
You can swap variables in python using
a, b = b, a
, so you can swap list elements with their indexes:Output:
为了这样做,您也需要接受其他整数作为参数。
a,b = b,a
更容易交换
代码:
输出:
In order to do so, you need to accept the other integers as arguments as well.
And swapping is easier as
a, b = b, a
Code:
Output:
您可以修改swaplst函数以在任何给定的索引上交换元素:
you can modify the swapLst function to swap the elements at any given indices: