[英]List append 2 tuples reversed
I have a list like this 我有这样的清单
Test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
I want to append reversed elements in each tuple (I might be using wrong language) 我想在每个元组中添加反向元素(我可能使用的语言错误)
Here is the example 这是例子
I want to append this 我想附加这个
(5.0, 3.0), (7.0, 1.0), (4.0, 1.0)
If possible I don't want to append duplicates in the list 如果可能的话,我不想在列表中添加重复项
I tried this 我试过了
Test.append(Test[i][1]),(Test[i][0]) # (where i = 0 to 1)
but failed 但失败了
Didn't quite follow what you meant with i
though. 虽然
i
不太理解您的意思。 But a simple list comprehension will work 但是简单的列表理解就可以了
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])
Or just use a normal for-loop. 或者只是使用普通的for循环。 You can either append to the same list, or add items to new list and then extend.
您可以追加到同一列表,也可以将项目添加到新列表,然后扩展。 I personally prefer new list and then extend as otherwise you will end up iterating over the newly appended items (which makes no difference aside from efficiency)
我个人更喜欢新列表,然后再进行扩展,否则您将最终遍历新添加的项目(除了效率之外,没有任何区别)
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)]
To reverse the elements in the list, you can simply use reversed
function, and recreate the list, like this 要反转列表中的元素,您可以简单地使用
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)]
If possible I don't want to append duplicates in the list
如果可能的话,我不想在列表中添加重复项
As you want to remove the duplicates as well, the best option would be to use collections.OrderedDict
like this 当您也想删除重复项时,最好的选择是使用
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.