gpt4 book ai didi

Python 相当于 Ruby 的 .find

转载 作者:数据小太阳 更新时间:2023-10-29 08:56:30 24 4
gpt4 key购买 nike

我正在尝试将以下 Ruby 方法实现为 Python 方法:

CF = {:metre=>{:kilometre=>0.001, :metre=>1.0, :centimetre=>100.0}, :litre=>{:litre=>1.0, :millilitre=>1000.0, :imperial_pint=>1.75975}}

def common_dimension(from, to)
CF.keys.find do |canonical_unit|
CF[canonical_unit].keys.include?(from) &&
CF[canonical_unit].keys.include?(to)
end
end

行为如下:

>> common_dimension(:metre, :centimetre)
=> :metre

>> common_dimension(:litre, :centimetre)
=> nil

>> common_dimension(:millilitre, :imperial_pint)
=> :litre

实现它的“Pythonic”方法是什么?

最佳答案

下面是您的 ruby​​ 逻辑的 python 代码。

CF={"metre":{"kilometre":0.001, "metre":1.0, "centimetre":100.0}, "litre":{"litre":1.0, "millilitre":1000.0, "imperial_pint":1.75975}}

def common(fr,to):
for key,value in CF.items():
if (fr in value) and (to in value):
return key

print(common('metre','centimdetre'))
metre
print(com('metre','centimdetre'))
None
******************

single line function
com = lambda x,y:[key for key,value in CF.items() if (x in value) and (y in value)]
print(com('metre','centimdetre'))
['metre']

关于Python 相当于 Ruby 的 .find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54627480/

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