![](/img/trans.png)
[英]How can I create a dictionary from two lists, one list is the keys, the other contains nested values?
[英]How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one?
我需要初始化一个字典来启动列表中元素的聚类模型,当我进行聚类时,我将按索引合并元素,但随后我需要显示我在列表。 所以我想过做一个字典并在每次聚类时合并这些值。
假设我有以下列表:
fileList = ["doc1", "doc2", "doc3", "doc4", "doc5"]
我的想法是用它们创建一个字典,索引作为键,字符串作为值:
fileDict = {0: ["doc1"], 1: ["doc2"], 2: ["doc3"], 3: ["doc4"], 4: ["doc5"]}
然后在集群过程之后,我可以更改键的名称并打印:
clustersDict = {1: ["doc1", "doc2", "doc3"], 2: ["doc4", "doc5"]}
现在,我尝试的是:
clustersDict = dict.fromkeys([i for i in range(len(listFiles)), name for name in listFiles])
问题是它附加了整个文件列表的每个键,而不仅仅是一个,我尝试使用索引 I 但它显然说它没有定义,而且我真的不知道如何继续,因为我是对 Python 很陌生。
谢谢!
fileList = ["doc1", "doc2", "doc3", "doc4", "doc5"]
{v:[k] for v, k in enumerate(fileList)}
结果:
{0: ['doc1'], 1: ['doc2'], 2: ['doc3'], 3: ['doc4'], 4: ['doc5']}
只需使用枚举:
fileList = ["doc1", "doc2", "doc3", "doc4", "doc5"]
result = dict(enumerate([f] for f in fileList))
print(result)
输出
{0: ['doc1'], 1: ['doc2'], 2: ['doc3'], 3: ['doc4'], 4: ['doc5']}
使用字典理解
fileList = ["doc1", "doc2", "doc3", "doc4", "doc5"]
filedict = {idx:val for idx,val in enumerate(fileList)}
我需要初始化一个字典以启动列表中元素的聚类模型,然后在进行聚类时,我将按元素的索引合并这些元素,但随后需要显示列表中的字符串列表。 因此,我考虑过制作字典并在每次将它们聚类时合并这些值。
因此,假设我有以下列表:
fileList = ["doc1", "doc2", "doc3", "doc4", "doc5"]
我的想法是用索引作为键,将字符串作为值,从中创建一个字典:
fileDict = {0: ["doc1"], 1: ["doc2"], 2: ["doc3"], 3: ["doc4"], 4: ["doc5"]}
然后在集群过程之后,我可以更改键的名称并打印:
clustersDict = {1: ["doc1", "doc2", "doc3"], 2: ["doc4", "doc5"]}
现在,我尝试的是:
clustersDict = dict.fromkeys([i for i in range(len(listFiles)), name for name in listFiles])
问题在于,它对每个键都附加了整个文件列表,而不仅仅是一个文件,我尝试使用索引I,但显然它未定义,而且我真的不知道如何继续前进,因为Python的新手。
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.