列表作为值列表 - 找到最长列表

use*_*095 4 python dictionary list set

我有一个字典,其中的值是列表.删除重复项后,我需要找到哪个键具有最长列表作为值.如果我找到最长的列表,这将无法工作,因为可能有很多重复.我尝试了几件事,但没有什么是正确的.

Ada*_*ith 14

d = # your dictionary of lists

max_key = max(d, key= lambda x: len(set(d[x])))
# here's the short version. I'll explain....

max( # the function that grabs the biggest value
    d, # this is the dictionary, it iterates through and grabs each key...
    key = # this overrides the default behavior of max
        lambda x: # defines a lambda to handle new behavior for max
            len( # the length of...
                set( # the set containing (sets have no duplicates)
                    d[x] # the list defined by key `x`
                   )
               )
   )
Run Code Online (Sandbox Code Playgroud)

由于max迭代字典键的代码(这是字典遍历的字符,by by.for x in dict: print x将打印每个键dict),它将返回它在应用我们构建的函数时找到的具有最高结果的键(即这是lambda做什么的key=.你可以在这里做任何事情,这就是它的美丽.但是,如果你想要键和值,你可能会做这样的事情....

d = # your dictionary

max_key, max_value = max(d.items(), key = lambda k,v: len(set(v)))
# THIS DOESN'T WORK, SEE MY NOTE AT BOTTOM
Run Code Online (Sandbox Code Playgroud)

这是不同的,因为d我们传递的d.items()是一个由元组d的键和值构建的元组列表,而不是传递,这是一个字典.例如:

d = {"foo":"bar", "spam":['green','eggs','and','ham']}
print(d.items())
# [ ("foo", "bar"),
#   ("spam", ["green","eggs","and","ham"])]
Run Code Online (Sandbox Code Playgroud)

我们不再看字典,但所有数据仍然存在!使用我使用的unpack语句更容易处理:max_key, max_value =.这与您的工作方式相同WIDTH, HEIGHT = 1024, 768.max它仍然像往常一样工作,它遍历我们构建的新列表d.items()并将这些值传递给它的key函数(lambda k,v: len(set(v))).您还会注意到我们不必这样做len(set(d[k])),而是直接操作v,因为d.items()已经创建了d[k]值,并且lambda k,v使用了相同的unpack语句来分配键k和值v.

魔法!显然,魔术不起作用.我在这里没有深入挖掘lambda,实际上,s不能自己解压缩值.相反,做:

max_key, max_value = max(d.items(), key = lambda x: len(set(x[1])))
Run Code Online (Sandbox Code Playgroud)