将字符串和数字作为字符串拆分为两个列表以便浮动它们

Split list with string and numbers as string to two in order to float them

你好,我需要拆分一个包含字符串的列表。有些字符串是单词,有些是数字。

我必须漂浮它们

x = ['2','45','0.34','4.5','text','wse','56',]

我尝试了什么:

FloatList = [x for x in Mylist if isinstance(x, float)]

但它打印空列表:

[]

你能指出我哪里错了吗?

所以我需要从数字字符串中过滤单词,在 sep 中浮动字符串。名单

这些都是字符串对象,'1.2'不是1.2:

>>> type('1.2')
<class 'str'>
>>> type(1.2)
<class 'float'>
>>> 

你应该在检查之前将它们转换为浮动对象。

因为 float() 函数将引发 ValueError 如果它无法隐藏您提供的字符串,您可以使用 try...except 来捕获该错误:

>>> l = []
>>> x = ['2','45','0.34','4.5','text','wse','56'] 
>>> for i in x:
...     try:
...         l.append(float(i))
...     except ValueError:
...         pass

>>> l
[0.34, 4.5, 2, 45, 56]