python如何创建txt_如何通过读取.txt文件为每个键创建包含多个“列表”的Python字典?...

我有一个大文本文件,看起来像:

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,24,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,21,22','151,24,26','48,24,31'],

2: ['14,6,8','98,13,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, c1, c2, c3 = map(int, line.split())

result.setdefault(idx, []).append((c1, c2, c3))

标签:python,dictionary

来源: https://codeday.me/bug/20190727/1553848.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值