我想删除多余的元组,但保留外观顺序。我看着类似的问题。这个问题在numpy.array中查找唯一行看起来很有希望,但是以某种方式对我不起作用。
我可以在此答案中使用熊猫(https://stackoverflow.com/a/14089586/566035),但我更喜欢不使用熊猫,以便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')
就效率而言,这不是很好,但是它是非常简单的可读代码,并且可以用于较小的列表:
sorted(set(data), key=data.index)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句