-1

My script gives 2 string lists, a and b . I want to convert them to float lists to do some calculations, but the lists have some gaps. For example, i have a = ["1"," ","3","4"] and i want to fill those gaps with 0 and have this a = ["1","0","3","4"]

2 Answers2

1
a = list(map(lambda x: float(x) if x else .0, a))
vZ10
  • 2,468
  • 2
  • 23
  • 33
1

Using a list-comprehension.

a = ["1", " ", "3", "4"]

[float(i) if i.strip() else 0. for i in a]
# [1.0, 0.0, 3.0, 4.0]

The strip() part is to make " " String evaluated to False.

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

orginal source

Kruupös
  • 5,097
  • 3
  • 27
  • 43