[GIS] TypeError: “unsupported operand type(s) for /: ‘int’ and ‘list'” in QGIS

pyqgispythonqgistypeerrorvector

In a academic project I've produced a small python script for watershed analysis. This script relates shapefiles attributes and generates a .txt file.

I am trying to adjust the script to use within the QGIS environment. When I use it, it shows the following error:

unsupported operand type (s) for /: 'int' and 'list' See log for more details

In logs we can see:

2019-01-03T21:10:57 2   Uncaught error while executing algorithm
        Traceback (most recent call last):
          File "C:/PROGRA~1/QGIS2~1.18/apps/qgis-ltr/./python/plugins\processing\core\GeoAlgorithm.py", line 203, in execute
            self.processAlgorithm(progress)
          File "C:/PROGRA~1/QGIS2~1.18/apps/qgis-ltr/./python/plugins\processing\script\ScriptAlgorithm.py", line 381, in processAlgorithm
            exec((script), ns)
          File "<string>", line 123, in <module>
          File "<string>", line 35, in densidade_rios
        TypeError: unsupported operand type(s) for /: 'int' and 'list'

Here is the code:

from qgis.core import *
import math

# Function    
def densidade_rios(valor_total_rios, valor_area_bacia):
    dr = valor_total_rios / valor_area_bacia
    return dr

# Loading dreinage and watershed layers
dlayer = QgsVectorLayer(Drenagem, "drenagem", "ogr")
blayer = QgsVectorLayer(Bacia, "bacia", "ogr")

# Dreinage attributes
dfeatures = dlayer.getFeatures()
# Listing values per column
listdfeatures = list(zip(*dfeatures))

# Max and min order values
maxordem = max(listdfeatures[0])
minordem = min(listdfeatures[0])

# Counting features of channel hierarchy (dreinage layer values)
ordem = minordem
hierarquia = []
while (ordem <= maxordem):
    contagem = listdfeatures[0].count(ordem)
    hierarquia.append(contagem)
    ordem += 1

# Total of rivers - quantity of first order rivers (dreinage layer values)
totalrios = hierarquia[0]

# Watershed attributes    
areabh = blayer.getValues(blayer.fields()[0].name())[0]

# Using function    
dr = densidade_rios(totalrios, areabh)

Attribute table values of drenagem layer:

enter image description here

Attribute table values of bacia layer:

enter image description here

Best Answer

As mentioned by Michael Stimson the error is because a list was used where a number was expected.

densidade_rios is returning the result of a division, hence areabh (which is the division's denominator) needs to be a value:

areabh = blayer.getValues('Area_km2')[0][0] # where 'blayer.fields()[0].name()' is the field name 'Area_km2'.

Another way of getting areabh would be:

areabh = [f['Area_km2'] for f in blayer.getFeatures()][0]
Related Question