如何通过读取.txt文件为每个键创建包含多个“列表”的Python字典
发布时间:2020-12-20 11:54:48 所属栏目:Python 来源:网络整理
导读:我有一个大文本文件,看起来像: 1 27 21 221 151 24 261 48 24 312 14 6 82 98 13 16... 我想用它创建一个字典.每个列表的第一个数字应该是字典中的键,应该采用以下格式: {1: [(27,21,22),(151,24,26),(48,31)],2: [(14,6,8),(98,13,16)]} 我有以下代码(总
我有一个大文本文件,看起来像:
1 27 21 22 1 151 24 26 1 48 24 31 2 14 6 8 2 98 13 16 . . . 我想用它创建一个字典.每个列表的第一个数字应该是字典中的键,应该采用以下格式: {1: [(27,21,22),(151,24,26),(48,31)],2: [(14,6,8),(98,13,16)]} 我有以下代码(总点数是文本文件第一列中的最大数字(即字典中的最大键)): from collections import defaultdict info = defaultdict(list) filetxt = 'file.txt' i = 1 with open(filetxt,'r') as file: for i in range(1,num_cities + 1): info[i] = 0 for line in file: splitLine = line.split() if info[int(splitLine[0])] == 0: info[int(splitLine[0])] = ([",".join(splitLine[1:])]) else: info[int(splitLine[0])].append((",".join(splitLine[1:]))) 哪个输出 {1: ['27,22','151,26','48,31'],2: ['14,8','98,16']} 我想要这个字典的原因是因为我想在给定键的字典的每个“内部列表”中运行for循环: for first,second,third,in dictionary: .... 我不能用我当前的代码执行此操作,因为字典的格式略有不同(它在上面的for循环中需要3个值,但是接收的值超过3个),但它可以使用第一个字典格式. 任何人都可以建议解决这个问题吗? 解决方法result = {} with open(filetxt,'r') as f: for line in f: # split the read line based on whitespace idx,c1,c2,c3 = line.split() # setdefault will set default value,if the key doesn't exist and # return the value corresponding to the key. In this case,it returns a list and # you append all the three values as a tuple to it result.setdefault(idx,[]).append((int(c1),int(c2),int(c3))) 编辑:由于您希望键也是一个整数,您可以将int函数映射到拆分值,如下所示 idx,c3 = map(int,line.split()) result.setdefault(idx,[]).append((c1,c3)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |