gpt4 book ai didi

python - 如果列表不是 None 则获取列表的第一个元素 : Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:16:02 29 4
gpt4 key购买 nike

这是我的问题:

我正在用 Python 进行 LDAP 搜索。搜索将返回一个字典对象:

{'mail':['user@mail.com'],'mobile':['07852242242'], 'telephoneNumber':['01112512152']}

如您所见,返回的字典包含列表值。

有时会找不到结果:

{'mail':None, 'mobile':None, 'telephoneNumber':['01112512152']}

为了提取所需的值,我使用 get() 以避免在字典项不存在时出现异常。

return {"uname":x.get('mail')[0], "telephone":x.get('telephoneNumber')[0], "mobile":x.get('mobile')[0]}

我想像上面那样返回我自己的字典,只有字符串值,但我正在努力寻找一种有效的方法来检查列表是否为 None 并继续遇到索引错误或类型错误:

(<type 'exceptions.TypeError'>, TypeError("'NoneType' object is unsubscriptable",)

有没有办法在列表上使用 get() 方法,这样如果列表为 None 就不会抛出异常???

{"uname":x.get('mail').get(0)}

在不使用的情况下获取列表的第一个值或返回 None 的最有效方法是什么:

if isinstance(x.get('mail'),list):

if x.get('mail') is not None:

最佳答案

如果你想扁平化你的字典,你可以这样做:

>>> d = {'mail':None, 'mobile':None, 'telephoneNumber':['01112512152']}
>>>
>>> dict((k,v and v[0] or v) for k,v in d.items())
{'mail': None, 'mobile': None, 'telephoneNumber': '01112512152'}

如果您还想过滤掉 None 值,那么您可以这样做:

>>> dict((k,v[0]) for k,v in d.items() if v)
{'telephoneNumber': '01112512152'}

关于python - 如果列表不是 None 则获取列表的第一个元素 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9327158/

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