列表附加2个元组反转

时间:2015-11-27 01:53:42

标签: python list tuples

我有一个像这样的列表

Test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]

我想在每个元组中添加反转元素(我可能使用了错误的语言)

以下是示例

我想追加这个

(5.0, 3.0), (7.0, 1.0), (4.0, 1.0)

如果可能,我不想在列表中附加重复项

我试过这个

Test.append(Test[i][1]),(Test[i][0]) # (where i = 0 to 1)

但失败了

3 个答案:

答案 0 :(得分:2)

虽然没有完全遵循你对i的意思。但是一个简单的列表理解将起作用

myList = [(5.0, 3.0), (7.0, 1.0), (4.0, 3.0), (3.0, 5.0)]
myList.extend([(y, x) for x, y in myList if (y, x) not in myList])

或者只是使用正常的for循环。您可以附加到同一列表,也可以将项目添加到新列表然后进行扩展。我个人更喜欢新的列表然后扩展,否则你将最终迭代新添加的项目(这与效率没有区别)

myList = [(5.0, 3.0), (7.0, 1.0), (4.0, 3.0), (3.0, 4.0)]
res = []
for x, y in myList:
    if (y, x) not in myList and (y, x) not in res:
        res.append((y, x))
myList.extend(res)

#Output 
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0), (3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]

答案 1 :(得分:1)

要反转列表中的元素,您只需使用reversed函数,然后重新创建列表,就像这样

>>> test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
>>> [tuple(reversed(item)) for item in test]
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0)]
  

如果可能,我不想在列表中附加重复项

如果您想要删除重复项,最好的选择是使用collections.OrderedDict这样的

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(tuple(reversed(item)) for item in test).keys())
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0)]

答案 2 :(得分:0)

>>> Test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
>>> T = [(i[1], i[0]) for i in Test]
>>> T
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0)]