2

I have one field with a list of integers. I want to fill another field with the sum of those integers. When I print the results on the Python console, everything is fine. But I don't know how to fill every cell: when I try return, all the features have the same result as the first one. I understand why that happens but I cannot figure out what is the right way. I've spent a while now looking for examples but no one corresponds exactly to what I'm looking for. In the code below "ESPESSURA" is the field with the list of integers (ex: 40,67), attrs[13] the field I want to fill.

from qgis.core import *
from qgis.gui import *
from qgis.utils import iface
@qgsfunction(args=0,group='Custom')
def sum_list_str(value1,feature,parent):
    lyr = iface.activeLayer()
    features = lyr.getFeatures()
    idx = lyr.fields().lookupField('ESPESSURA')
    for feat in features:
        attrs = feat.attributes()
        attrs[13]=sum([int(i) for i in attrs[idx].split(',')])
        #return(attrs[13]) -> takes the first result and fills everything with it
        #print(attrs[13]) -> prints the values I'm looking for
        #lyr.updateFeature() -> QgsVectorLayer.updateFeature(): not enough arguments
        #lyr.updateFeatures() -> 'QgsVectorLayer' object has no attribute 'updateFeatures'
    #lyr.commitChanges()

(I'm pretty sure there are a lot of inelegant things in the code. Any comment is welcome.)

0
1

One solution using expressions:

@qgsfunction(args='auto', group='Math')
def get_list_sum(value, feature, parent):
    return sum([int(e) for e in value.split(",")])

Then write this expression (e.g., in the field calculator):

get_list_sum("ESPESSURA")

With my own data and fields:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.