gpt4 book ai didi

python - 在python中遍历对象

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:37 26 4
gpt4 key购买 nike

如何编写这段代码而不是无限期地重复自己?

fields = row.split('__')

if len(fields) == 1:
foo = getattr(bundle.obj, fields[0])
elif len(fields) == 2:
foo = getattr(getattr(bundle.obj, fields[0]), fields[1])
elif len(fields) == 3:
foo = getattr(getattr(getattr(bundle.obj,
fields[0]), fields[1]), fields[2])
# etc ..

最佳答案

使用reduce() :

foo = reduce(getattr, fields, bundle.obj)

或者一个简单的循环:

foo = bundle.obj
for field in fields:
foo = getattr(foo, field)

关于python - 在python中遍历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459355/

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