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 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]
推荐阅读
- windows - 强制关闭正在运行的 dotnet 进程
- r - 使用函数迭代 tibble 中的列
- javascript - Javascript计算从一年到下一年的变化增加或减少
- java - 如何在子类方法java中调用超类变量
- python - Pywinauto:未找到 click() 方法
- xml - ODI12C:无法从 XML 文件加载控制字符
- django - 尝试使用 ForeignKey 时 UNIQUE 约束失败
- java - “setDataSource 失败”异常
- unity3d - Unity 无法构建到 Android
- php - 有条件地删除单个页面的 Storefront 手持菜单