python删除列表中的空字符串,从列表中删除空字符串

I just started Python classes and I'm really in need of some help. Please keep in mind that I'm new if you're answering this.

I have to make a program that takes the average of all the elements in a certain list "l". That is a pretty easy function by itself; the problem is that the teacher wants us to remove any empty string present in the list before doing the average.

So when I receive the list [1,2,3,'',4] I want the function to ignore the '' for the average, and just take the average of the other 4/len(l). Can anyone help me with this?

Maybe a cycle that keeps comparing a certain position from the list with the '' and removes those from the list? I've tried that but it's not working.

解决方案

You can use a list comprehension to remove all elements that are '':

mylist = [1, 2, 3, '', 4]

mylist = [i for i in mylist if i != '']

Then you can calculate the average by taking the sum and dividing it by the number of elements in the list:

avg = sum(mylist)/len(mylist)

Floating Point Average (Assuming python 2)

Depending on your application you may want your average to be a float and not an int. If that is the case, cast one of these values to a float first:

avg = float(sum(mylist))/len(mylist)

Alternatively you can use python 3's division:

from __future__ import division

avg = sum(mylist)/len(mylist)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值