python - 如何从元组列表中删除重复项但保持原始顺序

标签 python sorting numpy unique

我想删除多余的元组但保留出现的顺序。我看了类似的问题。这个问题Find unique rows in numpy.array看起来很有希望,但不知何故它对我不起作用。

我可以像这个答案( https://stackoverflow.com/a/14089586/566035 )一样使用 pandas,但我不喜欢使用 pandas,这样 py2exe 生成的可执行文件会很小。

import numpy as np

data = [('a','z'), ('a','z'), ('a','z'), ('1','z'), ('e','z'), ('c','z')]

#What I want is:
    array([['a', 'z'],
           ['1', 'z'],
           ['e', 'z'],
           ['c', 'z']], 
          dtype='|S1')

#What I have tried:
# (1) numpy.unique, order not preserved
np.unique(data)

    array([['a', 'z'],
           ['c', 'z'],
           ['1', 'z'],
           ['e', 'z']], 
          dtype='|S1')

# (2) python set, order not preserved
set(data)

    set([('1', 'z'), ('a', 'z'), ('c', 'z'), ('e', 'z')])

# (3) answer here : https://stackoverflow.com/a/16973510/566035, order not preserved
a = np.array(data)
b = np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
_, idx = np.unique(b, return_index=True)

a[idx]

    array([['1', 'z'],
           ['a', 'z'],
           ['c', 'z'],
           ['e', 'z']], 
          dtype='|S1')

最佳答案

这在效率方面并不是很好,但是是非常简单的可读代码,并且可以适用于较小的列表:

排序(设置(数据),key=data.index)

关于python - 如何从元组列表中删除重复项但保持原始顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25650376/

相关文章:

python - 如何以编程方式将在线网页目标元素打印为图像?

python - 如何从映射文件中读取行?

python - 如何在 pandas 中组合数据框选择查询?

python - 将集合转换为列表时,什么决定项目顺序?

PHP 按 id 对 stdClass 对象数组进行排序

python - 如何创建一个 numpy N 维零数组,只有一个元素等于 1?

python - 连接到与登录到 google colab 的不同的 google 驱动器

javascript - 为html表格实现数字排序?

python - 在 numpy 中计算高于阈值的数组值的最快方法

python-3.x - Pandas Dataframe 使用合并过滤结果。编码解码问题