簡體   English   中英

列表追加2個元組反轉

[英]List append 2 tuples reversed

我有這樣的清單

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)

但失敗了

雖然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)]

要反轉列表中的元素,您可以簡單地使用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)]
>>> 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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM