简体   繁体   中英

Sum of first elements in nested lists

I am trying to get the first element in a nested list and sum up the values.

eg.

nested_list = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']]
print sum(i[0] for i in nested_list)

However, there are times in which the first element in the lists None instead

nested_list = [[1, 'a'], [None, 'b'], [3, 'c'], [4, 'd']]
new = []
for nest in nested_list:
    if not nest[0]:
        pass
    else:
        new.append(nest[0])
print sum(nest)

Wondering what is the better way that I can code this?

First of all, Python has no null , the equivalent of null in languages like Java, C#, JavaScript, etc. is None .

Secondly, we can use a filter in the generator expression. The most generic is probably to check with numbers :



print sum(i[0] for i in nested_list )

Number will usually make sure that we accept int s, long s, float s, complex es, etc. So we do not have to keep track of all objects in the Python world that are numerical ourselves.

Since it is also possible that the list contains empty sublists, we can also check for that:

from numbers import Number

print sum(i[0] for i in nested_list if  isinstance(i[0], Number))

Just filter then, in this case testing for values that are not None :

sum(i[0] for i in nested_list if i[0] is not None)

A generator expression (and list, dict and set comprehensions) takes any number of nested for loops and if statements. The above is the equivalent of:

for i in nested_list:
    if i[0] is not None:
        i[0]  # used to sum()

Note how this mirrors your own code; rather than use if not ...: pass and else , I inverted the test to only allow for values you actually can sum. Just add more for loops or if statements in the same left-to-right to nest order if you need more loops with filters, or use and or or to string together multiple tests in a single if filter.

In your specific case, just testing for if i[0] would also suffice; this would filter out None and 0 , but the latter value would not make a difference to the sum anyway:

sum(i[0] for i in nested_list if i[0])

You already approached this in your own if test in the loop code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM