Adding items inside an array

2

I have the following array:

    soma_campos = null
    tabela = [
        ['A-B', 22, 0.045,  0.1,    0.005],
        ['A-C', 50, 0.020,  0.1,    0.002],
        ['A-D', 48, 0.021,  0.1,    0.002],
        ['A-E', 29, 0.034,  0.1,    0.003]
    ]

How can I make the variable soma_campos receive the sum of all the second values of each array?

    
asked by anonymous 10.11.2018 / 23:53

1 answer

1

Only by making a correction, what you've created is actually a list and not an array, the syntax for creating an array would be something like array([1, 2, 3]) , see here a quick explanation of the differences between the two.

To get the values that are in the second item of each sublist, you can use list comprehensions , which " provides a concise way of creating lists "(more on the subject here and here ). The syntax would be this:

valores = [sub_lista[1] for sub_lista in tabela]

This code using list comprehensions does the equivalent of a for loop:

valores = []
for sub_lista in tabela:
    valores.append(sub_lista[1])

And to sum these values you can use the sum() function, directly passing the resulting list of values. The final code looks like this:

tabela = [
    ['A-B', 22, 0.045, 0.1, 0.005],
    ['A-C', 50, 0.020, 0.1, 0.002],
    ['A-D', 48, 0.021, 0.1, 0.002],
    ['A-E', 29, 0.034, 0.1, 0.003]
]
soma_campos = sum([sub_lista[1] for sub_lista in tabela])
print('Soma dos campos: ', soma_campos)

See an example on Ideone .

    
11.11.2018 / 00:47