Uys*_*l M 0 python python-3.x python-3.4 python-3.5
我试图将列表中的''更改为整数或浮点数.让我们说我有一个清单
allprices = ['', '', '', 1.2, 3.2, 1.8, '', '', '', '', '', '']
Run Code Online (Sandbox Code Playgroud)
我想将空字符串更改为浮点数或整数.我不确定该部分,但很确定它们必须在最后浮动,因为我要计算平均值.为此,我有另一个名单
averages = []
Run Code Online (Sandbox Code Playgroud)
列表"allprices"是由子列表基本上形成的元素列表的列表.它有6个级别.我试图将''替换为0并且它有效.但无法弄清楚如何使用命令进行更改.我在这里或其他论坛中找到了一些示例和命令,但对我没有用.我尝试的第一件事是
var = ''
var1= 0
var = var1
Run Code Online (Sandbox Code Playgroud)
但这会产生一些错误.我也试过直接把它变成一个浮点但是也没用.请帮助或指导我另一个标题,以便我能弄明白.顺便说一下,我是编程新手,所以我尝试做的可能看起来不是一个解决这个问题的方便方法,但我很高兴,只要它对我有用.
在计算平均值时,只需忽略它们:
>>> allprices = ['', '', '', 1.2, 3.2, 1.8, '', '', '', '', '', '']
>>> sum(x for x in allprices if x)/len(allprices)
0.5166666666666667
Run Code Online (Sandbox Code Playgroud)
注意 - 这取决于'非真实性' ''.如果你有列表元素,否则它们是"真实的"(例如' ')但应该被过滤,请适当调整你的if子句:
>>> allprices = ['', '', '', 1.2, 3.2, 1.8, '', '', '', '', '', ' ']
>>> sum(x for x in allprices if isinstance(x, (float, int)))/len(allprices)
0.5166666666666667
Run Code Online (Sandbox Code Playgroud)
如果您可能具有不是的数字类int或float使用要过滤的抽象基类Numbers:
>>> import numbers
>>> sum(x for x in allprices if isinstance(x, numbers.Number))/len(allprices)
0.5166666666666667
Run Code Online (Sandbox Code Playgroud)
如果你想真正替代''与0使用列表理解:
>>> [e if e else 0 for e in allprices]
[0, 0, 0, 1.2, 3.2, 1.8, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
要么,
>>> [e if isinstance(e, (float, int)) else 0 for e in allprices]
[0, 0, 0, 1.2, 3.2, 1.8, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |