Python:更改元组列表中的元组顺序

时间:2011-07-22 12:18:39

标签: python

我有一个像这样的元组列表:

ListOfTuples = [(var1,var2,var3,var4,var5), 
    (var6,var7,var8,var9,var10), 
    (var11,var12,var13,var14,var15),
    (var16,var17,var18,var19,var20)]

我想交换两个元组,即列出如下列表:

ListOfTuples = [(var1,var2,var3,var4,var5), 
    (var6,var7,var8,var9,var10), 
    (var16,var17,var18,var19,var20)
    (var11,var12,var13,var14,var15)]

我尝试了以下尝试失败:

ListOfTuples[2], ListOfTuples[3] = ListOfTuples[3] , ListOfTuples[2]

有谁能告诉我该怎么做?

2 个答案:

答案 0 :(得分:2)

您的代码对我来说很好。我也尝试过下面的代码,它对我有用:

data = [(1,2,3), (3,4,5), (5,6,7), (7,8,9)]
data[2:] = reversed(data[2:])
>>> [(1, 2, 3), (3, 4, 5), (7, 8, 9), (5, 6, 7)]

我已尝试以下列方式使用条件:

data = [(1,2,3), (3,4,5), (5,6,7), (7,8,9)]
for i,x in enumerate(data):
    if i+1 < len(data) and x[0] < data[i+1][0]:        
        data[i], data[i+1] = data[i+1], data[i]
>>> [(3, 4, 5), (5, 6, 7), (7, 8, 9), (1, 2, 3)]

答案 1 :(得分:-2)

希望这会有所帮助:

temp = ListOfTuples[2]
ListOfTuples[2] = ListOfTuples[3]
ListOfTuples[3] = temp