[英]Find unique list of tuples irrespective of order inside tuple
Given input:给定输入:
[('is','my','order'), ('my','order', 'is'), ('temp', 'ques'), ('ques','temp')]
Desired output:所需的 output:
[('is','my','order'), ('temp', 'ques')]
In the output, the order of the tuple or the order of the contents of tuple doesn't matter.在 output 中,元组的顺序或元组内容的顺序无关紧要。
Because for you order doesn't matter, you can use set
to achieve this:因为对于您的订单无关紧要,您可以使用set
来实现这一点:
>>> input_list = [('is','my','order'), ('my','order', 'is'), ('temp', 'ques'), ('ques','temp')]
>>> set(tuple(sorted(l)) for l in input_list)
set([('ques', 'temp'), ('is', 'my', 'order')])
Firstly sort the content of each nested tuple to ensure your set considers tuples with common items as same.首先对每个嵌套元组的内容进行排序,以确保您的集合将具有共同项目的元组视为相同。 Then I am type-casting it again to tuple
because sorted
returns list
which are unhashable.然后我再次将其类型转换为tuple
,因为sorted
后的返回list
是不可散列的。 Finally, set
removes duplicate entries of your tuples.最后, set
删除元组的重复条目。
Please refer "set" documentation for more details.有关详细信息,请参阅“设置”文档。
You can sort each of the sublists and then add them to a list, dropping all duplicates您可以对每个子列表进行排序,然后将它们添加到列表中,删除所有重复项
output_list = []
for tup in map(sorted, tuple_list):
if tup not in output_list:
output_list.append(tup)
print(output_list)
mytuples = [('one','two'), ('two','one)]
myset=set()
for x in mytuples:
myset.update(x)
print(myset)
output {'two', 'one'}
this will give you a set of all the unique values in your dataset.这将为您提供数据集中所有唯一值的集合。 maybe not helpful也许没有帮助
so you may have to check each tuple against every other tuple with the same length assuming you want to keep the tuple structure因此,假设您要保留元组结构,您可能必须检查每个元组与具有相同长度的每个其他元组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.