如何在Python中识别列表元素的正确类型?
问题分析与解决方案
你的代码存在几个关键问题,导致无法得到预期输出:
- 容器类型错误:
types_list是字典,每次循环会覆盖id和type的值,应该用列表存储每个元素的类型信息字典。 - 判断对象错误:你用了枚举的索引
x做类型判断,而不是目标元素i。 - 类型判断逻辑错误:
- 非空字符串转
bool都会得到True,不能直接用bool(i)判断,需要检查字符串内容是否为'True'或'False'。 - 类型判断顺序有误:
int类型的字符串(如'23')也能转成float,所以要先判断int,再判断float,最后兜底判断字符串。
- 非空字符串转
修正后的代码
list_of_elements = ['string', '23', '11.04', 'True'] types_list = [] for idx, elem in enumerate(list_of_elements, 1): # 先判断布尔类型 if elem in ('True', 'False'): types_list.append({'id': idx, 'type': 'Boolean'}) # 再判断整数类型 elif elem.isdigit(): types_list.append({'id': idx, 'type': 'Integer'}) # 然后判断浮点数类型 elif '.' in elem and elem.replace('.', '', 1).isdigit(): types_list.append({'id': idx, 'type': 'Float'}) # 最后兜底为字符串类型 else: types_list.append({'id': idx, 'type': 'String'}) print(types_list)
输出结果
[ {'id': 1, 'type': 'String'}, {'id': 2, 'type': 'Integer'}, {'id': 3, 'type': 'Float'}, {'id': 4, 'type': 'Boolean'} ]
注:如果需要处理负数的情况,可以在整数和浮点数的判断里加入对负号的检查,比如修改isdigit的判断逻辑为elem.lstrip('-').isdigit()(整数)和elem.lstrip('-').replace('.', '', 1).isdigit()(浮点数)。
内容的提问来源于stack exchange,提问作者Balaramakrishna Paritala
相关产品推荐
相关产品推荐

