我有一个大文本文件,看起来像:
1 27 21 22
1 151 24 26
1 48 24 31
2 14 6 8
2 98 13 16
.
.
.
Run Code Online (Sandbox Code Playgroud)
我想用它创建一个字典。每个列表的第一个数字应该是字典中的键,并且应该采用以下格式:
{1: [(27,21,22),(151,24,26),(48,24,31)],
2: [(14,6,8),(98,13,16)]}
Run Code Online (Sandbox Code Playgroud)
我有以下代码(总分是文本文件第一列中的最大数字(即字典中的最大键)):
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:])))
Run Code Online (Sandbox Code Playgroud)
哪个输出
{1: ['27,21,22','151,24,26','48,24,31'],
2: ['14,6,8','98,13,16']}
Run Code Online (Sandbox Code Playgroud)
我想做这本字典的原因是因为我想对给定键的字典的每个“内部列表”运行 for 循环:
for first, second, third, in dictionary:
....
Run Code Online (Sandbox Code Playgroud)
由于字典的格式略有不同,我无法使用当前代码执行此操作(它在上面的 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)))
Run Code Online (Sandbox Code Playgroud)
编辑:由于您希望键也是整数,因此您可以在拆分值上使用map该int函数,如下所示
idx, c1, c2, c3 = map(int, line.split())
result.setdefault(idx, []).append((c1, c2, c3))
Run Code Online (Sandbox Code Playgroud)