【问题标题】:Nested for-loops and their formats嵌套 for 循环及其格式
【发布时间】:2016-12-10 21:35:18
【问题描述】:

我正在使用 Python 2.7。从以前的帖子中,我正在学习 Python,并且我已经从数组转移,现在我正在研究循环。我也在尝试使用数组进行操作。

 A1 = np.random.random_integers(35, size=(10.,5.))

 A = np.array(A1)

 B1 = np.random.random_integers(68, size=(10.,5.))

 B = np.array(B1)

 D = np.zeros(10,5) #array has 10 rows and 5 columns filled with zeros to give me the array size I want
 for j in range (1,5):
     for k in range (1,5):
          D[j,k] = 0
          for el in range (1,10):
               D[j,k] = D[j,k] + A[j] * B[k] 

我得到的错误是:使用序列设置数组元素

我的格式不正确吗?

【问题讨论】:

    标签: arrays python-2.7 loops for-loop


    【解决方案1】:

    因为A、B、D都是二维数组,所以D[j,k] 是单个元素,而 A[j](与 A[j,:] 相同)是一维数组,在这种情况下,它有 5 个元素。与 B[k] = B[k,:] 类似,即也是一个 5 元素数组。 因此 A[j] * B[k] 也是五元素数组,不能存储在单个元素的位置,因此会出现错误:将数组元素设置为序列。

    如果要从A和B中选择单个元素,那么最后一行应该是

        D[j,k] = D[j,k] + A[j,k] * B[j,k] 
    

    您的代码上的一些进一步的 cmets:

        # A is already a numpy array, so 'A = np.array(A1)' is redundant and can be omitted
        A = np.random.random_integers(35, size=(10.,5.))
    
        # Same as above                
        B = np.random.random_integers(68, size=(10.,5.))
    
        D = np.zeros([10,5]) # This is the correct syntax for creating a 2D array with the np.zeros() function
        for j in range(1,5):  
            for k in range(1,5):
                 # D[j,k] = 0   You have already defined D to be zero for all elements with the np.zeros function, so there is no need to do it again
                 for el in range(1,75):
                      D[j,k] = D[j,k] + A[j] * B[k]  
    

    编辑: 好吧,我没有足够的声誉来评论你的帖子@Caroline.py,所以我会在这里做:

    首先,记住python使用零索引,所以'range(1,5)'给你'[1,2,3,4]',这意味着你不会到达第一个索引,即索引0. 因此,您可能希望使用 'range(0,5)',它与 'range(5)' 相同。

    我可以看到您将 el 范围从 75 更改为 10。如果您不将 el 用于任何内容,则仅表示您在最后一行添加了 10 次。

    我不知道你想做什么,但是如果你想将A和B的倍数存储在D中,那么这样应该是对的:

        for j in range(10):  
            for k in range(5):
                  D[j,k] = A[j,k] * B[j,k]  
    

    或者只是

        D = A * B
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多