from numpy import *
import collections
array = [28000,35200,35200,35200,35700,36000]
rng = range(35000,37000)
for elem in array:
print elem
35200 35700 36000
这让我有了一个良好的开端,但我只需要范围列表中的重复项,这只是35200.我尝试在print elem下添加一行,例如 -
print elem
print [x for x, y in collections.Counter(a).items if y > 1]
但我得TypeError: 'numpy.float64' object is not iterable
。稍后将需要副本用于等式。如何将数组缩小到范围内的副本?
答案 0 :(得分:1)
items
是一个功能,您忘记了()
:
counterItems = collections.Counter(a).items()
print [x for x, y in counterItems if y > 1]
答案 1 :(得分:0)
另一种方法:
In [15]: a = [28000,35200,35200,35200,35700,36000]
In [16]: set([x for x in a if a.count(x) > 1])
Out[16]: set([35200])
答案 2 :(得分:0)
numpy
这样做的方式是:
>>> a=np.array([28000,35200,35200,35200,35700,36000])
>>> a[np.sum(a==a[...,np.newaxis], axis=1)>1]
array([35200, 35200, 35200])
>>> np.unique(a[np.sum(a==a[...,np.newaxis], axis=1)>1])
array([35200])
答案 3 :(得分:0)
在a
被排序的假设下,这可能是最快的方法(使用numpy
),包括范围限制:
import numpy
a = numpy.array([28000,35000,35200,35200,35200,35200,35700,36000])
left = a.searchsorted(35000, "left")
right = a.searchsorted(37000, "right")
section = a[left:right]
numpy.unique(section[section[1:] == section[:-1]])
#>>> array([35200])
通过在常规非numpy数组上使用bisect
模块,可以找到类似的加速。