Python 相当于 Ruby 的 .find

Python equivalent of Ruby's .find

我正在尝试将以下 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" 实现它的方法是什么?

下面 python 中的代码用于您的 ruby 逻辑。

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']

Ruby 和 Python 的其他选项。

对于Ruby:

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

from = :litre
to = :millilitre
cf.select { |k, v| ([from, to] - v.keys).empty? }.keys
#=> [:litre]

对于Python:

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

_from = 'millilitre'
_to = 'imperial_pint'
res = [ k for k, v in CF.items() if not bool(set([_from, _to]) - set(v.keys())) ]
#=> ['litre']