python - 从列表创建字典
问题描述
我有一个"testlist"
包含 4x 子列表的列表
[
[name1,ip1,mask1,group1],
[name2,ip2,mask2,group1],
[name3,ip3,mask3,group2],
[name4,ip4,mask4,group2]
]
我想从“testlist”中获取以下字典
{group1:[name1,name2], group2:[name3,name4]}
我在这里有一小段代码,它从每个子列表中获取“组”元素,然后使用获取的元素作为键更新字典。我坚持的是如何填充这些键的值?
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]:[]}
解决方案
在列表上使用“传统”循环(假设 name1、ip1 等在某处定义):
def test():
dic = {}
testlist = [
[name1, ip1, mask1, group1],
[name2, ip2, mask2, group1],
[name3, ip3, mask3, group2],
[name4, ip4, mask4, group2]
]
for each in testlist:
if each[3] not in dic:
dic[each[3]] = []
dic[each[3]].append(each[0])
return dic
推荐阅读
- django - 创建模型并通过 id 与嵌套序列化程序链接现有模型
- r - 有没有办法在 ggplot 中包含一个不在离散比例限制中的因素?
- python - ModuleNotFoundError:没有名为“keras.backend.tensorflow_backend”的模块
- awk - 如何提高这个 awk 脚本的速度
- java - 在 Request Android Studio 中祝酒
- java - 如何将 com.lowagie.text.Image 转换为 InputStream?
- javascript - ThreeJS:我们可以跳过鼠标事件吗?
- git - 克隆或拉取时在 GIT 存储库中保留回车/换行
- c++ - 收到错误“在 Juce 框架中分配抽象类类型的对象?
- python - 从 spacy 模型中删除训练数据