Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有一种方法可以在python中迭代更改列表元素的位置?_Python_Python 3.x_List_Loops_Arraylist - Fatal编程技术网

有没有一种方法可以在python中迭代更改列表元素的位置?

有没有一种方法可以在python中迭代更改列表元素的位置?,python,python-3.x,list,loops,arraylist,Python,Python 3.x,List,Loops,Arraylist,我有这样一个列表,我想迭代地更改第二个元素(索引1处的元素)的位置。比如, 迭代1: swepttour = [ (39.57, 26.15), (36.26, 23.12), (40.56, 25.32), (37.52, 20.44), (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37

我有这样一个列表,我想迭代地更改第二个元素(索引1处的元素)的位置。比如,

迭代1:

swepttour = [
    (39.57, 26.15), (36.26, 23.12), (40.56, 25.32), (37.52, 20.44), 
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]
迭代2:

swepttour = [
    (39.57, 26.15), (40.56, 25.32), (36.26, 23.12), (37.52, 20.44), 
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]

有办法吗?第一个和最后一个元素必须是稳定的。

您可以替换列表的切片,这是转换它们的常用方法。逐步浏览列表,并用交换的相同2个元素替换2个元素序列。首先,从数据开始

swepttour = [
    (39.57, 26.15), (40.56, 25.32), (37.52, 20.44), (36.26, 23.12),    
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]
然后去掉它,选择一个序列,使示例更容易在实际操作中看到

swepttour = [
    (39.57, 26.15), (36.26, 23.12), (40.56, 25.32), (37.52, 20.44), 
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]
然后遍历标记范围并交换2个元素切片

swepttour = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

对首先你应该自己试试。如果您有特定问题,那么您可以在这里询问您的代码。使用索引进行迭代(使用
range()
),而不是列表本身,只需按索引交换元素。提示:您可以使用
sweptour[index1],sweptour[index2]=sweptour[index2],sweptour[index1]
交换元素。非常感谢您,先生,我真的很感激。与上面的建议不同,我确实尝试过,但效果不好,所以我不想分享一段无用的代码……再次非常感谢
print(swepttour)
for i in range(1, len(swepttour)-2):
    swepttour[i:i+2] = swepttour[i+1], swepttour[i]
    print(swepttour)