简体   繁体   English

是否有另一种方法可以在没有 for 循环的情况下做同样的事情?

[英]Is there an alternate way to do the same without for loop?

I have two numpy arrays A and l .我有两个 numpy arrays Al The dimension of A is (n, x, y) and the dimension of l is (n,1) . A的维度是(n, x, y)l的维度是(n,1) I get the result as follows:我得到的结果如下:

res = []
for i in range(n):
    res.append(A[i, x, l[i])

This way of getting the result is very time consuming for a larger value of n .对于较大的n值,这种获取结果的方法非常耗时。 Is there an alternative to get the same result quickly?是否有替代方法可以快速获得相同的结果?

If 0<=l[i]<y for all values of i :如果0<=l[i]<y对于i的所有值:

>>> n,x,y = 4,5,6
>>> A = np.random.randint(0,10,(n,x,y))
array([[[3, 3, 3, 8, 7, 0],
        [8, 1, 1, 5, 3, 8],
        [0, 1, 0, 4, 1, 3],
        [2, 2, 1, 8, 6, 5],
        [2, 5, 9, 2, 6, 3]],

       [[9, 7, 4, 6, 7, 7],
        [1, 7, 0, 4, 9, 6],
        [8, 0, 8, 6, 7, 8],
        [1, 9, 7, 8, 7, 6],
        [2, 4, 6, 3, 6, 8]],

       [[2, 8, 5, 7, 9, 4],
        [7, 2, 2, 5, 2, 1],
        [0, 8, 6, 4, 1, 2],
        [6, 9, 9, 0, 2, 4],
        [9, 9, 1, 6, 7, 0]],

       [[3, 8, 4, 3, 5, 6],
        [5, 3, 7, 7, 4, 6],
        [9, 0, 7, 9, 2, 1],
        [1, 6, 2, 2, 9, 5],
        [5, 0, 9, 0, 5, 2]]])
>>> l = np.random.randint(low=0, high=y-1, size=(n,1))
array([[0],
       [1],
       [3],
       [1]])
>>> x0 = 2
>>> res = []
>>> for i in range(n):
        res.append(A[i, x0, l[i])

>>> res
[array([0]), array([0]), array([4]), array([0])]

numpy : numpy

>>> A[range(n), 2, l.flatten()]
array([0, 0, 4, 0])

what about list comprehension?列表理解呢?

res=[A[i, x, l[i] for i in range(n)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Pythonic while循环中执行迭代名称/变量的替代方法 - Alternate way to do Iterative name/variables in Pythonic while loop 有没有办法增加循环的速度或更快的方式来做同样的事情而不使用for循环? - Is there a way to increse the speed of the loop or a faster way to do the same thing without using for loop? 在同一循环中的相对路径和绝对路径之间交替 - Alternate Between Relative and Absolute Path in Same Loop 在不使用 for 循环的情况下在 Pandas 中执行此操作的正确方法 - Proper way to do this in pandas without using for loop 有没有办法在熊猫中做到这一点而无需使用循环? - Is there a way to do this in pandas without using loop? 使用 excel.xls,是否有其他方法可以执行以下操作? - Working with excel .xls, Is there an alternate way to do the below? 在 python 中组合没有“For Loop &amp; If else”的行数据的替代选项 - Alternate options to combine rows data without "For Loop & If else" in python 在不使用索引值的情况下处理for循环中的备用元素 - Processing alternate element in for loop without using index value 什么是在循环中在两个函数之间交替的pythonic方法 - What is the pythonic way to alternate between two functions in a loop 有没有一种方法可以在Tornado(Python)的同一循环中进行数据包的输入和输出? - Is there a way to do input and output of packets in the same loop in Tornado (Python)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM