Skip to main content
 首页 » 编程设计

python之因使用太多 for 循环、if 和 else 语句而感到困惑

2024年10月24日6unruledboy

我正在为地理信息系统软件 QGIS 开发一个插件。我创建了一个 QTableWidget 并希望从中提取值:

问题是,我使用了很多 for 循环和 if else 语句,直到最后几行,它们似乎都有效美好的。我现在似乎无法遵循逻辑,因为 print constraint_name 行仅打印出最后一个值“Example_2”。我可以将其从相应的 else 语句中取出,然后它将正确打印所有值,但我需要将其设置在一个条件内:

qTable = self.dockwidget.tableWidget  # QTableWidget 
example_group = root.findGroup('Main group')  # Group containing sub groups 
all_items = [] 
gis_map = QgsMapLayerRegistry.instance().mapLayersByName( "Map" )[0]  # Layer map in QGIS 
idx = gis_map.fieldNameIndex("Rank")  # Get "Rank" attribute field from gis_map 
for row in range(qTable.rowCount()): 
    for col in [0]:  # For first column "Constraint name" 
        constraint_item = qTable.item(row, col)                             
        constraint_name = str(constraint_item.text()) 
    for col in [1]:  # For second column "Rank" 
        item = qTable.item(row, col) 
        item_string = str(item.text()) 
        all_items.append(item_string) 
        for group in example_group.children():  # Search for specific group 
            if group.name() == "Sub group": 
                if len(set(all_items)) == 1:  # If all items are the same 
                    # If "Rank" field exists in layer map 
                    if idx == -1: 
                        print 'success' 
                    else:  
                        print 'fail'                         
                else: 
                    if idx == -1: 
                        print constraint_name 
                    else: 
                        print 'fail'    

有没有办法整理它并仍然得到正确的结果?

请您参考如下方法:

我衷心感谢指导我找到更有效解决方案的评论者,这是有效的工作代码(我相信它可以进一步完善):

qTable = self.dockwidget.tableWidget 
example_group = root.findGroup('Main group') 
all_items = [] 
gis_map = QgsMapLayerRegistry.instance().mapLayersByName( "Map" )[0] 
idx = gis_map.fieldNameIndex("Rank") 
for row in range(qTable.rowCount()): 
    constraint_item = qTable.item(row, 0)                             
    constraint_name = str(constraint_item.text()) 
    item = qTable.item(row, 1) 
    item_string = str(item.text()) 
    all_items.append(item_string) 
    for group in example_group.children(): 
        if group.name() == "Sub group": 
            if idx == -1: 
                if len(set(all_items)) == 1: 
                    print 'success' 
                else:  
                    print 'fail'                         
            else: 
                print constraint_name