【问题标题】:How to return index of item in MultiDimensional Array and check attributes of those items如何返回多维数组中项目的索引并检查这些项目的属性
【发布时间】:2016-07-18 21:09:18
【问题描述】:

我在遍历多维数组并返回元素的索引时遇到问题。我正在做的是创建一个在多维数组中移动的 MoveUp 函数。

目前我的 find 方法将返回多维数组第一个索引中第一个数组中对象的正确索引。多维数组之外的其余项将返回错误:

UnboundLocalError: 'local variable 'column' refrenced before assignment'

同样在 MoveUp 函数中我得到一个错误。我将字段数组中的一项设置为“活动”,我希望它成为在数组中向上移动的起点。但由于某种原因,我的代码给了我这个错误。

AttributeError: 'list' object has no attribute 'status'


    class Square:       
    def SetName(self, name):
        self.name = name

    def SetOwner(self,name):
        self.controlled_by = name

    def SetLED(self, name):
        self.led = name

    def SetPosition(self, position):
        self.posiion = position

    def SetStatus(self, status):
                self.status = status

B1_A = Square()
B1_A.SetName("B_R1_A")
B1_A.SetOwner("Open")
B1_A.SetLED("Off")
B1_A.SetStatus("UnActive")

B1_B = Square()
B1_B.SetName("B_R1_B")
B1_B.SetOwner("Open")
B1_B.SetLED("Off")
B1_B.SetStatus("UnActive")

B2_A = Square()
B2_A.SetName("B_R2_A")
B2_A.SetOwner("Open")
B2_A.SetLED("Off")
B2_A.SetStatus("UnActive")

B2_B = Square()
B2_B.SetName("R_R2_B")
B2_B.SetOwner("Open")
B2_B.SetLED("Off")
B2_B.SetStatus("UnActive")

B3_A = Square()
B3_A.SetName("R_R3_A")
B3_A.SetOwner("Open")
B3_A.SetLED("Off")
B3_A.SetStatus("UnActive")

R1_A = Square()
R1_A.SetName("R_R1_A")
R1_A.SetOwner("Open")
R1_A.SetLED("Off")
R1_A.SetStatus("UnActive")

R1_B = Square()
R1_B.SetName("R_R1_B")
R1_B.SetOwner("Open")
R1_B.SetLED("Off")
R1_B.SetStatus("UnActive")

R2_A = Square()
R2_A.SetName("R_R2_A")
R2_A.SetOwner("Open")
R2_A.SetLED("Off")
R2_A.SetStatus("UnActive")

R2_B = Square()
R2_B.SetName("R_R2_B")
R2_B.SetOwner("Open")
R2_B.SetLED("Off")
R2_B.SetStatus("UnActive")

R3_A = Square()
R3_A.SetName("R_R3_A")
R3_A.SetOwner("Open")
R3_A.SetLED("Off")
R3_A.SetStatus("UnActive")

# MultiDimensional Array
Field = [[B1_A,B1_B],[B2_A,B2_B],[B3_A],[R3_A],[R2_A,R2_B],[R1_A,R1_B]]

#Find Index of Element in MultiDimenstional Array
def find(l, elem):
    for row, i in enumerate(l):
        try:
            column = i.index(elem)
            return row, column
        except ValueError:
                return row, column
        return -1

print(find(Field, B1_A)) #Returns (0,0) Correct
print(find(Field, B1_B)) #Returns (0,1) Correct
#print(find(Field, B2_B)) #Throws Error

# Set a Square Status Active
B1_B.status ="Active"

def MoveUp():
        #Iterate through each item in Field
        for i in Field:
                #if item status equal to Active
                if i.status == "Active":
                        #if item index 3 item in the multidimensional array
                        if find(Field, i) == (2,0):
                        #current position is this index
                          current_position = (find(Field, i))
                          print(current_position)
                          #new position is this index + 1
                          new_position = current_position + 1
                          #old position if new position - 1
                          old_position = new_position - 1
                          #Set the servos status in the new postion to Active
                          Field(new_position).status = "Active"
                          #Set the servos status in the old position to UnActive
                          Field(old_position).status = "UnActive"

                        else:
                           #current position is this index
                           current_position = (find(Field, i))
                           #new position is this index + 2
                           new_position = current_position + 2
                           #old position if new position - 2
                           old_position = new_position - 2
                           #Set the servos status in the new postion to Active
                           Field(new_position).status = "Active"
                           #Set the servos status in the old position to UnActive
                           Field(old_position).status = "UnActive"

MoveUp()

【问题讨论】:

    标签: python arrays multidimensional-array attributeerror


    【解决方案1】:

    您遇到的第一个错误是因为您尝试返回不存在的值。

    #Find Index of Element in MultiDimenstional Array
    def find(l, elem):
        for row, i in enumerate(l):
            try:
                column = i.index(elem)
                return row, column
            except ValueError:
                #here is error column not exists.
                #return row, column 
                pass    
    
                #becouse it's normal that one of array don't have needed item
                #you should pass
    
    
        return -1
    
    print(find(Field, B1_A)) #Returns (0,0) Correct
    print(find(Field, B1_B)) #Returns (0,1) Correct
    print(find(Field, B2_B)) #will Return (1,1)
    

    您遇到的第二个错误是因为您尝试将 2d 数组用作 1d。

    def MoveUp():
    
        #Iterate through each item in Field
        for SubFields in Field: 
            #Every Field item is Array of Fields 
            #ie [B1_A,B1_B] You need to iterator over this sub field.
            for i in SubFields:
                #if item status equal to Active
    
                if i.status == "Active":
                    #if item index 3 item in the multidimensional array
                    if find(Field, i) == (2,0):
                        #current position is this index
                        current_position = (find(Field, i))
                        print(current_position)
                        #new position is this index + 1
    
                        # here is another error, but you will not get it with you test data
                        #current_position is tuple (2, 0)
                        #you can't add 1 to tuple
                        #I don't know what you trying to do here, so can't help with it.
                        new_position = current_position + 1 #ERROR!!!
                        #old position if new position - 1
                        old_position = new_position - 1 
                        #Set the servos status in the new postion to Active
                        Field(new_position).status = "Active" #also error Field is array not function
                        #Set the servos status in the old position to UnActive
                        Field(old_position).status = "UnActive"
    
                    else:
                        #current position is this index
                        current_position = (find(Field, i))
    

    更新:如果您想在任何深度的数组中查找(并获取)项目,请尝试以下操作:

    #really crazy multidimensional array
    Field = [ [ B1_A ],
              [
                  [ [B1_B],
                    [[B2_A]] ],
                  [ [B2_B, B3_A] ]
              ],
              [[ [ [[R3_A]] ],
                 [ [[R2_A],[R2_B]] ] ]] ]
    
    def find(l, needle):
        """Search for needle in l. 
           If found returns path to needle, otherwise return empty array"""
    
        def find_path( l, needle ):
            """Search for needle in l. 
               If found returns reversed path to needle, otherwise return empty array"""
            for index, item in enumerate(l):
                if type(item) is list:
                    sub_path = find_path( item, needle )
                    if sub_path:
                        sub_path.append( index )
                        return sub_path
                elif item == needle:
                    return [ index ]
    
            return []
    
    
        path = find_path( l, needle )
        path.reverse()
        return path
    
    def get_by_path( l, path ):
        """Get element of list l by it's path.
           If path is incorrect throw IndexError"""
        item = l
        for i in path:
            item = item[i]
        return item
    
    print( find( Field, B3_A ) ) # print [1, 1, 0, 1]
    print( get_by_path( Field, find( Field, B3_A ) ).name ) #print R_R3_A
    
    print( find( Field, R2_B ) ) # print [2, 0, 1, 0, 1, 0]
    print( get_by_path( Field, [2, 0, 1, 0, 1, 0] ).name )  #print R_R2_B
    

    【讨论】:

    • 更新:增加了可以搜索和检索多维列表中的项目的功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多