Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中创建词典_Python - Fatal编程技术网

Python 从列表中创建词典

Python 从列表中创建词典,python,Python,我有一个包含4个子列表的列表“testlist” [ [name1,ip1,mask1,group1], [name2,ip2,mask2,group1], [name3,ip3,mask3,group2], [name4,ip4,mask4,group2] ] 我想从“测试列表”中获取以下词典 我这里有一段代码,它从每个子列表中获取“group”元素,然后用获取的元素作为键更新字典。我一直想知道的是如何填充这些键的值 def test(): dic={} testlist = [

我有一个包含4个子列表的列表
“testlist”

[
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]
我想从“测试列表”中获取以下词典

我这里有一段代码,它从每个子列表中获取“group”元素,然后用获取的元素作为键更新字典。我一直想知道的是如何填充这些键的值

def test():
dic={}
testlist = [
            [name1,ip1,mask1,group1],
            [name2,ip2,mask2,group1], 
            [name3,ip3,mask3,group2],
            [name4,ip4,mask4,group2]
           ]
for each in testlist:
    dic.update{each[3]:[]}

考虑到
testlist
的每个子列表中的项目都是字符串,请尝试以下操作:

dic = {i : [j[0] for j in testlist if i==j[3]] for i in set([k[3] for k in testlist])}
以下是详细的相同代码:

unique_fourth_items = []
for i in testlist:
    unique_fourth_items.append(i[3])
unique_fourth_items = set(unique_fourth_items)
dic = {}
# Check in testlist for each item of unique_fourth_items list
for i in unique_fourth_items:
    temp = []
    for j in testlist:
        if j[3] == i:
            temp.append(j[0])
    dic[i] = temp

考虑到
testlist
的每个子列表中的项目都是字符串,请尝试以下操作:

dic = {i : [j[0] for j in testlist if i==j[3]] for i in set([k[3] for k in testlist])}
以下是详细的相同代码:

unique_fourth_items = []
for i in testlist:
    unique_fourth_items.append(i[3])
unique_fourth_items = set(unique_fourth_items)
dic = {}
# Check in testlist for each item of unique_fourth_items list
for i in unique_fourth_items:
    temp = []
    for j in testlist:
        if j[3] == i:
            temp.append(j[0])
    dic[i] = temp

在列表上使用“传统”循环(假设在某处定义了name1、ip1等):


在列表上使用“传统”循环(假设在某处定义了name1、ip1等):


testlist
变量或字符串的子列表中的项目是什么?如果它们是字符串,则应在引号内。字符串是否为group1和group2?是否为
testlist
变量或字符串的子列表中的项目?如果它们是字符串,那么它们应该在引号内。字符串group1和group2好吗?很漂亮,但是您不需要将集合强制转换到列表中。然而,它需要在原始列表上传递两次,在集合上传递另一次,而通过一个简单的循环,我们只需传递一次(我将发布一个答案)。这很有魅力。。谢谢你,迈克尔。。我再问你几个问题。。我只是想弄清楚那复杂的结构。。当我看到这样的结构,出于某种原因,我开始从头到尾阅读。。。据我所知,第一步是通过迭代testlist来创建一组包含每个子列表的'element 3'。很好,很优雅,但是您不需要将集合强制转换为列表。然而,它需要在原始列表上传递两次,在集合上传递另一次,而通过一个简单的循环,我们只需传递一次(我将发布一个答案)。这很有魅力。。谢谢你,迈克尔。。我再问你几个问题。。我只是想弄清楚那复杂的结构。。当我看到这样的结构,出于某种原因,我开始从头到尾阅读。。。据我所知,第一步是通过迭代testlist来创建一组包含每个子列表的“element 3”的单一列表。