Joseph Joseph - 6 months ago 20
Python Question

Confused by using too many for loops, if and else statements

I am developing a plugin for the GIS software, QGIS. I created a

QTableWidget
and wish to extract values from it:

Image

Problem is, I use a lot of
for
loops and
if
else
statements which, up until the last few lines, seems to work fine. I can't seem to follow the logic now as the line
print constraint_name
only prints off the last value "Example_2". I could take it out of its corresponding
else
statement and then it will print all values correctly but I need to set it inside a condition:

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'


Is there a way to tidy this up and still get the correct results?

Answer

My sincere thanks to the commenters who directed me to a much more efficient solution, here is the working code which works (I'm sure it can be refined further):

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 
Comments