Average of a list of numbers, stored as strings in a Python list

后端 未结 5 1712
一生所求
一生所求 2020-12-20 04:36

I want to calculate the average value of several lists in python. These lists contain numbers as strings. Empty string isn\'t zero, it means a missing value.

The be

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 05:11

    You can discard the square brackets. sum accepts generator expressions, too:

    total  = sum(int(n) if n else 0 for n in num)
    length = sum(1 if n else 0 for n in num)
    

    And since generators yields the value only when needed, you save the expensive cost of storing a list in the memory. Especially if you're dealing with bigger datas.

提交回复
热议问题