Add items within an array

Asked

Viewed 79 times

3

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 for that variable soma_campos receive the sum of all second values of each array?

1 answer

2


Just by making a correction, what you actually created is a list and not an array, the syntax to create 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 the list comprehensions, that "provides a concise way to create lists" (more on the subject here and here). The syntax would be this:

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

That code using list comprehensions makes the equivalent of a for loop:

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

And to add these values you can use the function sum(), directly passing the resulting list of values. The final code would look 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.

  • I think we can even take the [] and pass the direct comprehension: soma_campos = sum(item[1] for item in tabela)

  • Thank you very much, it worked perfectly. Sorry for the confusion, newbie yet. kk

  • Truth @hkotsubo, this way also works! But, why will it be? In the documentation it seems that always has to come wrapped with the [].

  • 1

    Tranquil @Sergiosacchettijunior! I don’t know Python at all myself, but I did some research to answer you and I’ve learned a few things! ;-)

  • 2

    Well, I’m still studying Python and I don’t know all the details, but when taking the [] the expression becomes a Generator. From what I’ve seen so far, it’s also timeless (just like a list, so it can be passed to sum), the difference is that Generator is Lazy (only processes the elements when requested, different from the list, which needs to have all the elements created). Although for small cases like this it shouldn’t make a difference...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.