[英]Append value or create and insert if the list doesn't exist?
I found myself always writing this kind of ugly snippet when I have to insert a value to a non-existing list:当我必须向一个不存在的列表插入一个值时,我发现自己总是写这种丑陋的片段:
if hasattr(obj, 'key'):
obj.key = []
obj.key.append(value)
Of course, I could use defaultdict(list)
, but in this use-case I cannot do it a priori.当然,我可以使用defaultdict(list)
,但在这个用例中我不能先验。
Is there a more pythonic yet simpler way of achieving this?有没有更pythonic但更简单的方法来实现这一点?
You could call setdefault
on the instance dict, ie您可以在实例字典上调用setdefault
,即
vars(obj).setdefault('key', []).append(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.