[英]Algorithm for reducing 2D list to its unique elements, maintaining order
Input: 输入:
[[102, 106], [106, 107], [101, 106], [104, 105, 106], [105], [103, 105], [104]]
Desired output: 所需的输出:
[102, 107, 101, 106, 105, 103, 104]
Each index of the original array is essentially the list of possibilities for the index in the result array. 原始数组的每个索引本质上是结果数组中索引的可能性的列表。 The goal being to represent each number one time in the result array. 目标是在结果数组中一次代表每个数字。 I'm having difficulty finding an appropriate type of algorithm for this task. 我很难找到适合此任务的算法类型。 What general approach would one take to a problem of this type? 对于此类问题,将采取哪种一般方法?
Here's a simple solution that just uses length of the set
of all the solutions as a key to max
: 下面是刚刚使用的长度的简单的解决方案set
所有的解决方案作为关键的max
:
>>> import itertools as it
>>> data = [[102, 106], [106, 107], [101, 106], [104, 105, 106], [105], [103, 105], [104]]
>>> max(it.product(*data), key=lambda x: len(set(x)))
(102, 107, 101, 106, 105, 103, 104)
You could use unique_everseen
after you have flattened the list: unique_everseen
平列表后,可以使用unique_everseen
:
# sample input
data = [[102, 106], [106, 107], [101, 106], [104, 105, 106], [105], [103, 105], [104]]
from more_itertools import unique_everseen
data = list(unique_everseen([a for sub in data for a in sub]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.