【问题标题】:Removing Empty elements in a list and converting the remaining into floats删除列表中的空元素并将剩余元素转换为浮点数
【发布时间】:2019-11-20 18:38:36
【问题描述】:

所以,基本上我有这个从 split() 方法得到的列表:

mylist=['', '3', '', '', '7.00', '', '', '', '21.00']

我想从列表中删除 ' ' 元素并将剩余的字符串转换为浮点数。请注意,我正在阅读的“”元素的位置或数量可能因字符串而异。

【问题讨论】:

  • 如果我的回答有帮助,请告诉我

标签: python python-3.x list list-comprehension


【解决方案1】:

使用这个:

mylist=['', '3', '', '', '7.00', '', '', '', '21.00']
clean_list = [float(i) for i in mylist if i !='']

print(clean_list)
[3.0, 7.0, 21.0]

【讨论】:

  • ValueError: could not convert string to float: I got this error
  • 你的代码运行完美,但我从 split() 方法中得到了这个字符串,我不知道这是否起到任何作用,因为我是 python 新手。
  • 准确发布您获得的列表。使用 split() 应该不是问题。我的答案适用于您在问题中发布的任何包含字符串的列表
  • 最好将代码/示例放在容易重现您面临的问题的位置。那么任何人都可以轻松地帮助您。
  • 好吧,我把它修好了,显然我在你之前有一行错误的代码并且没有工作。现在它完美地工作了非常感谢你
【解决方案2】:
result = [float(x) for x in mylist if x]

【讨论】:

  • 嗨 py_dude,我认为这是一个很好的答案,空序列和集合默认为 false。也许您想更详细地解释一下?
  • @StupidWolf 你刚刚解释了一切。我还能为您做什么?
  • 大声笑。只是希望你添加更多,并减少被删除的机会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
相关资源
最近更新 更多