查找数组中只出现一次的项

2024-10-04 05:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维数组。在这种情况下,每个行向量都被认为是感兴趣的量。我要做的是返回所有作为一个数组出现一次的所有行,以及作为第二个数组多次出现的所有行。在

例如,如果数组是:

a=[[1,1,1,0], [1,1,1,0], [5,1,6,0], [3,2,1,0], [4,4,1,0], [5,1,6,0]]

我想返回两个数组:

^{pr2}$

保持秩序是很重要的。我编写的代码如下:

def singles_nonsingles(array):
#returns the elements that occur only once, and the elements
#that occur more than once in the array
singles=[]
nonsingles=[]
arrayhash=map(tuple, array)

for x in arrayhash:
    if (arrayhash.count(x)==1):
        singles.append(x)

    if (arrayhash.count(x)>1):
        nonsingles.append(x)

nonsingles=array(nonsingles)
singles=array(singles)

return {'singles':singles, 'nonsingles':nonsingles}

现在,我很高兴地说这是可行的,但不高兴地说它非常慢,因为我的一个典型数组是30000(rows)x10 elements/row=300000个elements。有人能给我一些关于如何加快速度的建议吗??如果这个问题很简单,我很抱歉,我是Python新手。如果Python使用的是scinpy/7。在


Tags: theinifthatcount情况数组elements
3条回答

第一个只返回没有重复的single/no-single数组的列表,第二个返回有重复的数组

def comp (multi):
    from collections import defaultdict

    res = defaultdict(int)

    for vect in multi:
        res[tuple(vect)] += 1

    singles = []
    no_singles = []

    for k in res:
        if res[k] > 1:
            no_singles.append(list(k))
        elif res[k] == 1:
            singles.append(list(k))

    return singles, no_singles

def count_w_repetitions(multi):
    from collections import defaultdict

    res = defaultdict(int)

    for vect in multi:
        res[tuple(vect)] += 1

    singles = []
    no_singles = []

    for k in res:
        if res[k] == 1:
            singles.append(list(k))
        else:
            for i in xrange(res[k]):
                no_singles.append(list(k))


    return singles, no_singles

在Python2.7或更高版本中,可以使用collections.Counter来计算出现的次数:

def unique_items(iterable):
    tuples = map(tuple, iterable)
    counts = collections.Counter(tuples)
    unique = []
    non_unique = []
    for t in tuples:
        if counts[t] == 1:
            unique.append(t)
        else:
            non_unique.append(t)
    return unique, non_unique

我想你的问题是你在做一个in测试。这有没有(n)性能。在

构建一个dict,然后用它来计算每一行的操作应该更快。在

编辑:代码中有一个不必要的enumerate();我把它去掉了。在

from collections import defaultdict

def singles_nonsingles(array):
    #returns the elements that occur only once, and the elements
    #that occur more than once in the array
    singles=[]
    nonsingles=[]
    d = defaultdict(int)

    t = [tuple(row) for row in array]

    for row in t:
        d[row] += 1

    for row in t:
        if d[row] == 1:
            singles.append(row)
        else:
            nonsingles.append(row)

    return {'singles':singles, 'nonsingles':nonsingles}

以下是只返回唯一行的版本:

^{pr2}$

相关问题 更多 >