从列表python中仅选择数字

时间:2018-04-16 03:47:20

标签: python python-3.x list pandas numpy

我有一个列表如下:

listing = ["some string", 0.235, -56.335, -0.889]

我正在尝试:

z = np.asarray(listing, dtype='float32')

但这会产生错误。所以我想只采用花车,所以列出将成为:

listing = [0.235, -56.335, -0.889]

提前致谢!

2 个答案:

答案 0 :(得分:0)

listing = ["some string", 0.235, -56.335, -0.889]
num_only = []
for item in listing:
    if isinstance(item, int) or isinstance(item, float):
        num_only.append(item)

或更好:

numbers_only = [num for num in listing if isinstance(num, (int, float))]

答案 1 :(得分:0)

np.asarray([num for num in listing if isinstance(num, float)])