首页 > 解决方案 > Python 代码跳过识别数字

问题描述

从父列表中获取数字并仅创建数字子列表的 python 程序。但是,输出不是完整的数字列表。什么都没试过。蟒蛇新手。

input = ['True','False',[1,2,3,4],2,1.2,4,0.44]
# str(i): changing int or float to str
    return [str(i) for i in l if (type(i) == int or type(i) == float) ]
    # append the  numbers if it is an int or a float
print(f"num_str = {num_str(input)}")

# Output:
# num_str = ['2', '1.2', '4', '0.44']
# 1 and 3 are missing in the list.

标签: python

解决方案


为简化起见,我将采用“更简单”的输入列表作为

input = ['True','False',1,2,3,4,2,1.2,4,0.44]

# Changed the '[1,2,3,4]' for '1,2,3,4'
# Than you can:
result_list = []
for item in input:
    if isinstance(item, (int,float)):
        result_list.append(item)
#
print(result_list)
[1, 2, 3, 4, 2, 1.2, 4, 0.44]

为了让它处理您提供的输入,最好查看输入的来源并考虑是否可以在列表中的列表中包含列表,例如

a = [ 1,2,3,[10,"a",40,[56,"b"]],5,"string"]

如果可以的话,递归检查当前项目是否为 Iterable 类型会很有趣,否则只需添加另一个 for 来处理

b = [1,2,3,[5,6,"string"],7]

推荐阅读