Python 如何在包含列表的字典中查找值的组合?

Python 如何在包含列表的字典中查找值的组合?,python,Python,所以…我想做一个小的“寻找你的对手”程序。我决定做一个函数,我可以用它来处理女孩们的不同特征…“金发”头发。。。。“蓝色”的眼睛…等等。。。 嗯……问题是我不知道如何查找函数的合并结果:cf(response,con1,cond2,cond3,cond4),我想合并函数的这两个结果: list_match= {"Mada":["yellow","green",],"Alexa":["blonde","brown"],"Sasha":["blue","readhead"],"Andreea":["

所以…我想做一个小的“寻找你的对手”程序。我决定做一个函数,我可以用它来处理女孩们的不同特征…“金发”头发。。。。“蓝色”的眼睛…等等。。。 嗯……问题是我不知道如何查找函数的合并结果:cf(response,con1,cond2,cond3,cond4),我想合并函数的这两个结果:

list_match= {"Mada":["yellow","green",],"Alexa":["blonde","brown"],"Sasha":["blue","readhead"],"Andreea":["cameleonic","brunett"]}

print ('welcome to the "Find your match quiz"')
print ("Let/'s begain")

eyes = input ("How should the eyes be?")
hair=input("How do you want the the hair to be?")

def cf(response,cond1,cond2,cond3,cond4):
    if response == (cond1):
        return response
    if response == (cond2):
        return response
    if response == (cond3):
        return response
    if response ==(cond4):
        return response
    else:
        return ("We don't have knowledge of this characteristic.")

cf(eyes,"green","brown","blue","cameleonic")
cf(hair,"yellow","blonde","readhead","brunett")

因此,我可以在上面的字典中查找结果之间的组合,以便获得字典中每个真实组合的键,最后打印女孩的姓名加上“You Find a match”字符串…

以下列表理解将给出具有匹配属性的姓名列表:

cf(eyes,"green","brown","blue","cameleonic")
cf(hair,"yellow","blonde","readhead","brunett") 
尝试:

这将接受尽可能多的条件,而无需添加越来越多的
if
语句

如果要让它返回多个名称,请将
返回
更改为
收益
。这将生成一个生成器对象,您可以这样打印它们:

def search(*args):
    for (key, value) in list_match.items():
        if value == list(args):
            return key


>>> list_match= {"Mada":["yellow","green",],"Alexa":["blonde","brown"],"Sasha":["blue","readhead"],"Andreea":["cameleonic","brunett"]}
>>> search("cameleonic", "brunett")
'Andreea'
如果参数的顺序无关紧要:

>>> list_match= {"Mada":["cameleonic","brunett"],"Alexa":["blonde","brown"],"Sasha":["blue","readhead"],"Andreea":["cameleonic","brunett"]}
>>> def search(*args):
    for (key, value) in list_match.items():
        if value == list(args):
            yield key
>>> ", ".join(name for name in search("cameleonic", "brunett"))
'Andreea, Mada'

你能更详细地解释一下代码是如何工作的吗?谢谢。订单似乎没有定下来。你不能指望眼睛在列表索引0处。也许一个类比一个简单的属性列表更好。只要你不介意偶尔的重叠(匹配棕色眼睛而不是棕色头发),你可以尝试“v中的眼睛和v中的头发”。我还建议使用一个实际的匹配函数,将该逻辑置于dict理解之外。关于基本python语法的详细解释,请在教程或文档站点上查找“dict理解”。(注:最吸引人的属性是“喜欢我”,然后是“是个好人”,尽管相貌很好。)你的回答给我提出了另一个问题……我不能用这个*args我可以用一些其他的操作符吗?从这里我可以看出争论的顺序很重要,我只想知道“cameleonic”和“brunett”是否在那本字典里,顺序对我来说并不重要。。。
>>> list_match= {"Mada":["cameleonic","brunett"],"Alexa":["blonde","brown"],"Sasha":["blue","readhead"],"Andreea":["cameleonic","brunett"]}
>>> def search(*args):
    for (key, value) in list_match.items():
        if value == list(args):
            yield key
>>> ", ".join(name for name in search("cameleonic", "brunett"))
'Andreea, Mada'
def search(*args):
    for (key, value) in list_match.items():
       if sorted(value) == sorted(args):
           yield key