如何从列表字典中查找第一个公共号码

时间:2015-06-10 17:24:27

标签: python list dictionary

我有一份列表字典。每个列表包含许多数字。列表可以有不同的长度。我希望在所有列表中找到第一个公共号码答案必须是一个功能

例如在这种情况下:

d = { 'case1' : [18, 17, 497, 298, 57, 82, 1], 'case2': [128, 184, 497,298,57, 1, 82], 'case3':[104,2828,3881, 497, 1, 38], 'case4': [392, 497, 573, 1]}

预期输出为:497 。我不想抓住1.我只是在寻找497。

我现在拥有的只有:

def find_first_common_number(dictionary_of_lists):
    for list_name in dictionary_of_lists:    #list name e.g. 'case1'
        for num1 in dictionary_of_lists[list_name]:
            #this is where I am going to have to find the first common 
            # number from all lists in the dictionary
            # the order this number appears in each list DOES NOT matter

感谢您对此的帮助。我查看了列表方法,因为我不熟悉Python,所以做不了多少。如果你能解释/评论你的方法会很棒。

3 个答案:

答案 0 :(得分:2)

def first_in_all(data):
    values = data.values()
    common_values = set(values[0]).intersection(*values[1:]) #this should create a set of all common values
    #im still not sure why order is important or how its determined for you
    #but if order is not important you might just return `common_values` here
    if not common_values:
       return None  #there were no common values
    for item in data[min(data.keys())]: 
        if item in common_values:
           return item #return first item that is found in the common_values set

答案 1 :(得分:2)

我可以尝试这种方式:

#!/usr/bin/python

d = { 'case1' : [18, 17, 497, 298, 57, 82],
      'case2': [128, 184, 497,298,57,82],
      'case3':[104,2828,3881, 497, 38],
      'case4': [392, 497, 573]
      }

k = d.values()
# This sort will bring the shortest list in the front 
# will loop base on the shortest list.(optimization)
k.sort(key = lambda s: len(s))

def find_first_common_number(k):
    # lets loop base on the shortest list.
    # k[0] is the first list 
    for y in k[0]:
       if all([y in x for x in k[1:]]):
           return y
    return False
print find_first_common_number(k)

输出:    497

答案 2 :(得分:1)

你可以做的一件事就是与& amp进行一场比较。操作

>>> d = { 'case1' : [18, 17, 497, 298, 57, 82], 'case2': [128, 184, 497,298,57,82], 'case3':[104,2828,3881, 497, 38], 'case4': [392, 497, 573]}
>>> a = set(d['case1']) & set(d['case2']) & set(d['case3']) & set(d['case4'])
>>> a
set([497])

DOCS

如果你想在一个函数中使用它,你就可以这样做。

def find_common(d):
    all = list(d.values())
    common = set(all[0]).intersection(*all[1:])
    if not len(common):
        return None
    return common

然而,我坚定地支持这样的观点,即没有第一个"项目。可能有这么多的用例存在重叠的第一个"第一个"这毫无意义