【问题标题】:Appending to dictionary of lists using max value使用最大值附加到列表字典
【发布时间】:2020-07-08 02:05:07
【问题描述】:

我有多个长度相等的列表,我想比较这些列表以便在列表字典中附加一些单词。我已经比较了这些列表以获得每个索引的最大数量。

maxlist = [2,9,6,4,8] #This is the list of max number from the three different lists

a_list = [2,1,4,2,8]
b_list = [1,9,6,3,4]
c_list = [0,3,2,4,1]

现在,我有另一个相同长度的单词列表:

words = ["boy", "girl", "git", "tall", "boss"]

我在这里要做的是将每个列表与 maxlist 进行比较,如果在同一索引的三个列表中的任何一个中找到 maxlist 中的数字,我想创建一个列表字典,将单词附加到那个特定的列表。所以我的最终结果将是:

对于索引 0,maxlist 是在 a_list 中找到的,所以我会有:

 {a_list: ["boy"]}

对于索引 1,在 b_list 中找到了 maxlist,所以我会有:

 {a_list: ["boy"], b_list: ["girl"]}

在将所有列表与 maxlist 进行比较后,我想要:

 {a_list: ["boy", "boss"], b_list:["girl","git"], c_list: ["tall"]}

我在这里以三个列表为例,但在我的例子中,我有 40 个列表。有没有有效的方法来实现这一点?我目前被卡住了。这是我目前正在编写的代码:

 label_data = {}
 for i in range(len(maxlist)):
   if maxlist[i] > 1: #I don't want to consider a max of 1.
     if maxlist == a_list[i]:
        if a_list in label_data:
           label_data["a_list"].append(words[i])
        else:
           dates_dict["key"] = [words[i]]

不确定上面的代码是否能正常工作,另外我必须继续为所有列表构建 if 函数。有什么有效的方法可以解决这个问题,请发布您的代码。

谢谢

【问题讨论】:

    标签: python


    【解决方案1】:

    通常在比较列表中的相应元素时,zip 非常有用。来自集合模块的defaultdict 也有助于创建列表字典:

    from collections import defaultdict
    
    label_data = defaultdict(list)
    
    words = ["boy", "girl", "git", "tall", "boss"]
    a_list = [2,1,4,2,8]
    b_list = [1,9,6,3,4]
    c_list = [0,3,2,4,1]
    
    # iterate over corresponding words and entries in your three lists
    for word, a, b, c in zip(words, a_list, b_list, c_list):
        m = max(a, b, c)
        # check for the max value and append accordingly
        if m == a:
            label_data['a_list'].append(word)
        elif m == b:
            label_data['b_list'].append(word)
        else:
            label_data['c_list'].append(word)
    
    

    哪些输出

    defaultdict(<class 'list'>, {'a_list': ['boy', 'boss'], 'b_list': ['girl', 'git'], 'c_list': ['tall']})
    

    【讨论】:

    • 另一个 Eniola 指南 - 当您想将变量名称用作 dict 键时,您可能应该重构这些变量,以便它们在开始时位于 dict 中。
    • @KennyOstrom 是的,但我认为 OP 所追求的字典在很大程度上解决了这个问题
    • @C.Nivs,如何从我的输出中排除 ?有什么想法吗?
    • 打印一个字典(或默认字典)是另一个问题,你应该能够管理它。您可以在迭代字典时打印键和值。
    猜你喜欢
    • 2017-11-15
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2023-03-23
    • 2016-01-16
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多