使用最大值追加到列表字典

2024-05-19 00:05:48 发布

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

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

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: ["boy"]}

对于索引1,maxlist位于b_列表中,因此我将有:

 {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函数。是否有任何有效的方法来解决这个问题,请张贴您的代码

谢谢


Tags: ofthe代码列表dataif字典单词
1条回答
网友
1楼 · 发布于 2024-05-19 00:05:48

通常在比较列表中的对应元素时,^{}非常有用。“集合”模块中的^{}还有助于创建列表字典:

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']})

相关问题 更多 >

    热门问题