在2D数组中添加列(Python)

时间:2014-06-23 17:59:53

标签: python arrays list

所以我试图添加2D数组的所有列,除了数组的前两列。如果行的总和大于或等于9且小于12,我希望函数打印行。以下是我的2D数组的示例,它是一个列表列表:

[[12606.000,  74204.000,     1.000,     1.000,     1.000,     1.000,     1.000,     0.000,     0.000],        
[12606.000,  105492.000,     0.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000],    
[12606.000,  112151.000,     1.000,     1.000,     0.000,     0.000,     0.000,     0.000,     0.000],     
[12606.000,  121896.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000,     0.000]]     

(删除了一些列以进行格式化)。 这是我的代码:

def sumBinRow(A):
    """Returns the list of employees recording data for at least nine months and fewer than twelve.
    """
    for i in range(len(A)):
        for j in range(len(A[i])):
            if 9 <= sum(A[i][j+2]) <12:
                print A[i]

我一直得到一个&#34;类型错误&#34;说&#39; int&#39;对象不可迭代。

4 个答案:

答案 0 :(得分:1)

基本上,您需要迭代每个列表,对于每个列表,从2开始从该列表中获取一部分,然后对其进行求和并进行比较。

def sumBinRow(A):
    """Prints the list of employees recording data for at least nine months and fewer than twelve.
    """
    for row in A:
        if 9 <= sum(row[2:]) < 12:
            print row

或在一行中导致为什么不:P

def sumBinRow(A):
    """Prints the list of employees recording data for at least nine months and fewer than twelve.
    """
    print [row for row in A if 9 <= sum(row[2:]) < 12]

答案 1 :(得分:0)

你应该这样总结。

def sumBinRow(A):
    """Returns the list of employees recording data for at least nine months and fewer than twelve.
    """
    for i in range(len(A)):
        sigma = 0
        for j in range(2,len(A[i])):
            sigma += A[i][j]
            if 9 <= sigma <12:
                print A[i]

答案 2 :(得分:0)

如果您使用NumPy执行此任务,则会更简单,更快捷:

import numpy as np

a = np.array([[12606.000,  74204.000,     1.000,     1.000,     1.000,     1.000,     1.000,     0.000,     0.000],
              [12606.000,  105492.000,     0.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000],
              [12606.000,  112151.000,     1.000,     1.000,     0.000,     0.000,     0.000,     0.000,     0.000],
              [12606.000,  121896.000,     0.000,     0.000,     0.000,     0.000,     0.000,     1.000,     0.000]])

b = a[:, 2:].sum(axis=1)
check = (b >= 9) & (b < 12)
print(a[check])

答案 3 :(得分:0)

问题在于你试图总结一些不是数组的东西:

if 9 <= sum(A[i][j+2]) <12: // A[j][j+2] is not iterable, it is an int

相反,您想使用slice函数:

if 9 <= sum(A[i][2:]) <12:  // This will sum sum all but first two elements

更加pythonic的方式是使用list comprehension。这可以通过一行代码完成:

A = [[12606, 74204 , 1, 1, 1, 1, 1, 0, 0],        
     [12606, 105492, 0, 0, 0, 0, 0, 0, 1],    
     [12606, 112151, 1, 1, 0, 0, 0, 0, 0],     
     [12606, 121896, 0, 0, 0, 0, 0, 1, 0]]

print [row for row in A if 9 <= sum(row[2:]) < 12]