如何从列表字典中找到第一个常用数字

2024-09-28 22:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本单子字典。每个列表都包含许多数字。列表可以有不同的长度。我希望找到所有列表中的第一个公共编号。答案必须是一个函数。你知道吗

例如,在这种情况下:

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。我不想抓一个。我只找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还不熟悉。如果你能解释/评论你的方法,那就太好了。你知道吗


Tags: ofthenameinnumber列表fordictionary
3条回答

您可以做的一件事就是与&;运算符进行一组比较

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

然而,我坚决支持没有“第一”项的观点。可能有很多用例存在重叠的“第一个”,这是毫无意义的

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

我可以这样试一下吗:

#!/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个

相关问题 更多 >