gpt4 book ai didi

python - 在字典列表中查找值匹配值

转载 作者:太空宇宙 更新时间:2023-11-03 13:02:20 25 4
gpt4 key购买 nike

我有一个看起来像这样的字典列表:

serv=[{'scheme': 'urn:x-esri:specification:ServiceType:DAP',
'url': 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/air.mon.anom.nobs.nc'},
{'scheme': 'urn:x-esri:specification:ServiceType:WMS',
'url': 'http://www.esrl.noaa.gov/psd/thredds/wms/Datasets/air.mon.anom.nobs.nc?service=WMS&version=1.3.0&request=GetCapabilities'},
{'scheme': 'urn:x-esri:specification:ServiceType:WCS',
'url': 'http://ferret.pmel.noaa.gov/geoide/wcs/Datasets/air.mon.anom.nobs.nc?service=WCS&version=1.0.0&request=GetCapabilities'}]

并且我想找到对应于 ServiceType:WMS 的 URL,这意味着从该列表中的字典中找到 url 键的值,其中 scheme 键具有值 urn:x-esri:specification:ServiceType:WMS

所以我得到了这个有效的方法:

for d in serv:
if d['scheme']=='urn:x-esri:specification:ServiceType:WMS':
url=d['url']
print url

产生

http://www.esrl.noaa.gov/psd/thredds/wms/Datasets/air.mon.anom.nobs.nc?service=WMS&version=1.3.0&request=GetCapabilities

但我刚刚看了Raymond Hettinger's PyCon talk最后他说,如果你能把它说成一个句子,它应该用一行 Python 来表达。

那么是否有一种更漂亮、更惯用的方式来实现相同的结果,或许只需要一行 Python?

谢谢,丰富

最佳答案

您列出的 serv 数组看起来像一个字典映射方案到 URL,但它并没有这样表示。不过,您可以使用列表理解轻松地将它转换为 dict,然后使用普通字典查找:

url = dict([(d['scheme'],d['url']) for d in serv])['urn:x-esri:specification:ServiceType:WMS']

当然,您可以保存字典版本以供将来使用(以使用两行为代价):

servdict = dict([(d['scheme'],d['url']) for d in serv])
url = servdict['urn:x-esri:specification:ServiceType:WMS']

关于python - 在字典列表中查找值匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15800595/

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