我正在尝试实现类似于ansible with_first_found的东西,
configuration = {
"fedora-27" : "edge-case options for fedora 27",
"ubuntu-14.04" : "edge-case options for ubuntu 14.04",
"fedora" : "as long as it's fedora, these options are fine",
"ubuntu" : "these options are good for all ubuntu versions",
"redhat" : "options for rpm distros",
"debian" : "try these options for anything remotely resembling debian",
"default" : "/if/all/else/fails",
}
if __name__ == "__main__":
distribution_release = "ubuntu-16.04"
distribution = "ubuntu"
os_family = "debian"
lookup = [
distribution_release,
distribution,
os_family,
"default"
]
for key in lookup:
if key in configuration:
first_found = configuration[key]
break
print(first_found)现在,这段代码做了我想做的事情,但我有一种感觉,有一种更好的方法来完成这种查找。这个for/if/break循环可以在一行程序中完成吗?
根据timgeb的评论,更接近我的目标。
first_found = next(configuration[key] for key in lookup if key in configuration)这可能有点难读。
发布于 2018-01-04 20:03:24
您的代码没有任何问题。
您可以通过构造一个生成器并在其上调用next来缩短它。
>>> demo = {1:2, 3:4, 5:6}
>>> next(demo[k] for k in (6,3,5) if k in demo)
4这还允许使用默认值:
>>> next((demo[k] for k in (0,-1,-2) if k in demo), 'default')
'default'https://stackoverflow.com/questions/48094725
复制相似问题