Python 将列表中的头尾两个元素对调
定义一个列表,并将列表中的头尾两个元素对调。
例如:
对调前 : [1, 2, 3] 对调后 : [3, 2, 1]
实例 1
def swapList(newList):
size = len(newList)
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
newList = [1, 2, 3]
print(swapList(newList))
size = len(newList)
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
newList = [1, 2, 3]
print(swapList(newList))
以上实例输出结果为:
[3, 2, 1]
实例 2
def swapList(newList):
newList[0], newList[-1] = newList[-1], newList[0]
return newList
newList = [1, 2, 3]
print(swapList(newList))
newList[0], newList[-1] = newList[-1], newList[0]
return newList
newList = [1, 2, 3]
print(swapList(newList))
以上实例输出结果为:
[3, 2, 1]
实例 3
def swapList(list):
get = list[-1], list[0]
list[0], list[-1] = get
return list
newList = [1, 2, 3]
print(swapList(newList))
get = list[-1], list[0]
list[0], list[-1] = get
return list
newList = [1, 2, 3]
print(swapList(newList))
以上实例输出结果为:
[3, 2, 1]
江宁知府
183***5240@qq.com
参考方法:
江宁知府
183***5240@qq.com
renmoji
564***23@qq.com
参考:
renmoji
564***23@qq.com