gpt4 book ai didi

python - "pythonic"是用一个元素创建一个列表还是让它为空的方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:15 24 4
gpt4 key购买 nike

假设有一个 Person 实例 personperson 可能有一个属性 id

我想编写一个函数,当属性为 None 或缺失时,它会得到一个空列表 [] 或列表 [12, ] 当属性 id 为 12 时。

def get_id_list(person):
try:
return [getattr(person, 'id'), ]
except AttributeError:
return []

这非常有效,但是是否有一种“pythonic”方式可以在没有 try-except block 的情况下并且可能在一行中执行此操作?

最佳答案

我会去

def get_id_list(person):
_id = getattr(person, 'id', None)
return [] if _id is None else [_id]

但是,确保始终定义属性是一种很好的做法,这样您就不必使用带有默认值的 getattr 或使用 hasattr 检查是否存在.

关于python - "pythonic"是用一个元素创建一个列表还是让它为空的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40257498/

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