python-3.x - 如何创建一个函数,将每个列表项标识为字符串、浮点数或整数,然后打印一个类似 [str, int....] 的列表
问题描述
我很难让它识别每个单独的列表项。我一直在尝试使用 [i] 但它不起作用......
def identify(list_obj):
stats = {}
for i in items:
if type(list_obj) == int:
print("int")
if type(list_obj) == str:
print("str")
if type(list_obj) == float:
print("float")
else:
print("null")
return list_obj
print(identify(list5))
解决方案
你循环,items
但你没有items
在你的代码中声明。
所以你应该循环list_object
指定每个的类型item
def identify(list_objects):
"""
It takes a list of objects and specifies the type of each object in the list.
"""
handler_dict = {
int: 'int',
str: 'str',
float: 'float',
list: 'list',
dict: 'dict'
}
return [handler_dict.get(type(obj), 'unknown') for obj in list_objects]
测试
>>> list_objects = [1, 'a', [1, 2], {'a': 1}, 1.0]
>>> print(identify(list_objects))
out: ['int', 'str', 'list', 'dict', 'float']
推荐阅读
- java - 使用 toObject 方法将快照转换为 POJO 时,将包含 Date 对象的代码转换为 Firebase.Timestamp 对象的最佳方法
- gluon-mobile - 不同屏幕分辨率的字体缩放
- javascript - 如何读取 csv 坐标并用 javascript 绘制它们?
- python-3.x - 从python3.6中的另一个包导入时“没有命名模块”
- go - 如果它启动并运行以获取连接,如何使用golang查询redis Db?
- kubernetes - AWS EKS:EKS 如何将第一个用户添加到 system:masters 组
- vue.js - 在循环中访问下一个索引对象的值 - Vue JS
- pdf - 如何获得字体 PostScript 名称?
- laravel - Laravel - 如何使嵌套用户独一无二
- c# - 我将如何计算程序将使用的处理核心/线程的数量 | C#