从列表中删除空字符串 [英] Remove empty string from list
问题描述
我刚刚开始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.
我必须编写一个程序,该程序采用某个列表"l"中所有元素的平均值.就其本身而言,这是一个非常简单的功能.问题是老师要我们在计算平均值之前删除列表中存在的任何空字符串.
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.
因此,当我收到列表[1,2,3,'',4]
时,我希望函数忽略平均值的''
,而取其他4/len(l)的平均值.谁能帮我这个?
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)
浮点平均值(假设python 2)
根据您的应用程序,您可能希望平均值是浮点数而不是整数.如果是这种情况,请首先将以下值之一转换为浮点数:
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)
或者,您可以使用python 3的除法:
Alternatively you can use python 3's division:
from __future__ import division
avg = sum(mylist)/len(mylist)
这篇关于从列表中删除空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!