gpt4 book ai didi

python:动态类型转换 - unicode 对象到 python 对象转换

转载 作者:行者123 更新时间:2023-11-30 22:15:53 25 4
gpt4 key购买 nike

这是我在数据管道项目中面临的问题。我有2个数据源。一个包含所有用户数据,另一个包含我们必须从用户数据处理到输出的所有列的元数据。

所以 python 擅长动态类型转换,就像我说的那样

a = float
b = "25.123"
c = a(b)
print(c)
>> 25.123

这就是我想要做的,我想动态输入强制类型转换值以便正确处理它们。该类型是从元数据数据源检索的。问题是当我对元数据进行 django 模型查询时,我得到了 unicode 对象。

a = model.objects.filter(id = 'id') # get the type variable from the meta-data
a = a[0]['type']
print(a)
>> u'float'
a("123.123")
>> TypeError: 'unicode' object is not callable

如何将 u'float' 转换为 float ?这种方法有更好的选择吗?我查看了this ,但是不起作用

接受所有建议

最佳答案

在第一个示例中,a = floata是内置函数,但在第二个示例中,a = u"float", a 是一个 unicode 字符串。如果您希望转换为内置类型的完整“动态性”而不需要创建映射,您可以这样做:

# for Python 2
a = u"float"
b = "123.123"
import __builtin__
print getattr(__builtin__, a.decode())(b)
# 123.123

# for Python 3+
a = u"float"
b = "123.123"
import builtins
print(getattr(builtins, a)(b))
# 123.123
<小时/>

我建议您不要使用eval()(如another answer建议),因为它可能会导致重大安全风险。这就是为什么我使用 __builtin__/builtins模块和 getattr() 来检索 float(...) 函数。

<小时/>

您还可以创建一个映射(即 dict),将 unicode 字符串映射到其相应的函数(由此 comment 建议):

# both Python 2 and 3
a = u"float"
b = "123.123"
mapping = {u"float": float, u"int": int, u"str": str, u"list": list}
print(mapping[a](b))
# 123.123

使用映射是最安全的方法,但它会将您的“动态性”限制为仅映射中列出的类型。

关于python:动态类型转换 - unicode 对象到 python 对象转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50148545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com