Python代码跳过识别数字

Python代码跳过识别数字,python,Python,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

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.

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

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]

如果您询问为什么不包括
input[2]
中的数字,那是因为type(input[2])的计算结果是list,而不是int或float。为什么跳过1和3个数字?输出是num_str=['2','1.2','4','0.44']你说的1和3是什么意思?您的预期输出是什么?请注意,
type([1,2,3,4])==list
不仅缺少1和3,而且不包括整个列表。2和4来自列表后面的值,因为它们属于int类型。