简体   繁体   English

用于将2D列表缩小为其唯一元素,保持顺序的算法

[英]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.

相关问题 从 2D 列表中获取唯一元素 - Get unique elements from a 2D list 计算二维列表中索引处唯一元素的数量 - Count number of unique elements at index in 2D list 从2D python列表中提取唯一元素并将其放入新的2D列表中 - extract unique elements from a 2D python list and put them into a new 2D list 获取 3d 列表中唯一元素的最低索引的有效算法 - Efficient algorithm to get the lowest index of unique elements in a 3d list 改组 PyTorch 中的两个二维张量并保持相同的阶相关性 - Shuffling two 2D tensors in PyTorch and maintaining same order correlation 删除二维 NumPy 数组中的二维唯一元素 - Delete 2D unique elements in a 2D NumPy array 二维列表中元素的平均值 - Average of elements in a 2d list 比较二维列表中的行并将具有相同元素的唯一行存储在另一个列表中的一行中 - compare rows in 2d list and store the unique row having same elements in a row in another list 用其他列表中的数据替换2D列表中的所有元素-使用唯一ID-Python - Replace All Elements in 2D List with Data from Other List - Using Unique ID - Python 在 Python 中,如果我有一个 2D 列表,如何将一个 2D 列表的元素转移到另一个 2D 列表但顺序不同? - In Python, if I have a 2D List, How do I transfer the elements of one 2D List into another 2D List but in different order?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM