简体   繁体   English

从排列中清除元组列表

[英]Clean a list of tuples from the permutations

I have a list of tuples that I generated thus: 我有一个我生成的元组列表:

frequencies = [(a, b, 40) for a in [x for x in range(20, 110, 10) if x != 90] for b in range(20, 90, 10)]\
+[(a, b, 40) for a in [x for x in range(20, 110, 10) if x != 90] for b in range(100, 175, 25)]\
+[(a, b, 40) for a in [x for x in range(20, 110, 10) if x != 90] for b in range(200, 400, 50)]

I would like to consider permutations sa (20, 60, 40) and (60, 20, 40) identical and so to keep only one of them. 我想考虑排列sa(20,60,40)和(60,20,40)相同,所以只保留其中一个。

My current approach is: 我目前的做法是:

# Clean permutations
frequencies2 = list()
for f in frequencies:
    possible = list(itertools.permutations(f))
    if len([p for p in possible if p in frequencies2]) == 0:
        frequencies2.append(f)

frequencies = frequencies2

I am quite sure there is a better way to do this, but I can't find it. 我确信有更好的方法可以做到这一点,但我找不到它。 Although this code isn't really aesthetic, it is only O(n²). 虽然这段代码不是很美观,但只有O(n²)。

Thanks for your help. 谢谢你的帮助。

If you want to filter out permutations after the generation is complete then you can simply sort the tuples and compare them: 如果要在生成完成后过滤掉排列,则可以简单地对元组进行排序并进行比较:

without_permutations = list({tuple(sorted(f)): f for f in frequencies}.values())

This builds a dict in which the sorted tuples point to the original tuples. 这构建了一个dict,其中排序的元组指向原始元组。 That way, later tuples will overwrite earlier permutations of themselves. 这样,后来的元组将覆盖自己的早期排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM