有没有办法加速这个Python循环?

2024-09-28 20:52:13 发布

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

我有一个二维np数组,它的列数是行数的100倍。例如,如果行数为1000,列数为100000,并且值都是整数。我的目标是为1000行索引中的每一行返回1000个唯一整数。列中的值并不都是唯一的(可能有重复项),因此我必须搜索每一行中的所有值,以选取前一个操作中尚未选取的行中的第一个整数值。我有一个可复制的循环,它可以很好地处理1000行左右的小数值行。但当涉及到处理超过10000行时,这是非常缓慢的。有没有更有效的方法来解决这个问题?你知道吗

import numpy as np
maxval = 5000
matrix = np.random.randint(maxval,size=(maxval, maxval*100))
neighbours = maxval - 1
indices = [] #this array will contain the outputs after the loop gets completed
for e in matrix:
    i = 0
    while i < neighbours:
        if e[i] in indices:
            i += 1
        else:
            indices.append(e[i])
            break 

Tags: the方法inimport目标np整数数组
3条回答

使用字典会快得多,但我不知道是否足够:

from collections import OrderedDict

indx = OrderedDict()

for e in matrix:
    i = 0
    while i < neighbours:
        v = e[i]
        if indx.get(v) is None:
            indx[v] = True
            break
        i += 1

results = list(indx.keys())

不是简单的方法,但是如果row有100000个元素,那么

import random

random.sample(set(row), 1000)

是从中随机抽取1000个独特的元素。你知道吗

注意事项:

  • 如果一个数字出现的频率比另一个高很多,它们仍然有相同的被选中的机会
  • 如果唯一值的数目小于1000,则会引发ValueError
  • 我不知道,可能会有一个和这两个一样的小家伙

可以使用set而不是列表进行查找:

import numpy as np
maxval = 50
matrix = np.random.randint(maxval,size=(maxval, maxval*100))
neighbours = maxval - 1
indices = set() #this array will contain the outputs after the loop gets completed
for e in matrix:
    i = 0
    while i < neighbours:
        if e[i] in indices:
            i += 1
        else:
            indices.add(e[i])
            break 

这是live example

相关问题 更多 >