gpt4 book ai didi

python - 将文本元素保存到python中的字典中

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:00 24 4
gpt4 key购买 nike

我有一个格式如下的文本文件:

attr1    1,3,7,6,8,12,24,56
attr2 1,2,3
attr4 56,45,48,23,24,25,29,90,56,57,58,59
attr5 1,2,3,45,6,7,8,9,34,33

我想创建一个字典,其中数字将是键,如果包含 attr,则每个键都必须包含在列表中。为了更具体地说明我写的例子,字典必须是:

    1: [attr1,attr2,attr5]
2: [attr2,attr5]
3: [attr1,attr2,attr5]
6: [attr1, attr5]
etc...

我尝试实现它并编写了以下代码,但它不起作用。这是我的代码:

file2 = open("attrs.txt","r")
lines2 = file2.readlines()
d = dict()
list1 = []
for x in lines2:
x = x.strip()
x = x.split('\t')
y = x[0]
list1.append(x[1].split(','))
for i in list1:
d[i] = y

最佳答案

你可以使用collections.defaultdict:

import collections
import re
file_data = [[a, list(map(int, b.split(',')))] for a, b in [re.split('\s+', i.strip('\n')) for i in open('filename.txt')]]
d = collections.defaultdict(list)
for a, b in file_data:
for i in b:
d[i].append(a)

print(dict(d))

输出:

{1: ['attr1', 'attr2', 'attr5'], 2: ['attr2', 'attr5'], 3: ['attr1', 'attr2', 'attr5'], 6: ['attr1', 'attr5'], 7: ['attr1', 'attr5'], 8: ['attr1', 'attr5'], 9: ['attr5'], 12: ['attr1'], 23: ['attr4'], 24: ['attr1', 'attr4'], 25: ['attr4'], 90: ['attr4'], 29: ['attr4'], 33: ['attr5'], 34: ['attr5'], 45: ['attr4', 'attr5'], 48: ['attr4'], 56: ['attr1', 'attr4', 'attr4'], 57: ['attr4'], 58: ['attr4'], 59: ['attr4']}

或者使用 itertools.groupby 的更短但更复杂的解决方案:

import itertools
new_data = list(itertools.chain(*[[[i, a] for i in b] for a, b in file_data]))
final_result = {a:[b for _, b in c] for a, c in itertools.groupby(sorted(new_data, key=lambda x:x[0]), key=lambda x:x[0])}

输出:

{1: ['attr1', 'attr2', 'attr5'], 2: ['attr2', 'attr5'], 3: ['attr1', 'attr2', 'attr5'], 33: ['attr5'], 6: ['attr1', 'attr5'], 7: ['attr1', 'attr5'], 8: ['attr1', 'attr5'], 9: ['attr5'], 12: ['attr1'], 34: ['attr5'], 45: ['attr4', 'attr5'], 48: ['attr4'], 56: ['attr1', 'attr4', 'attr4'], 90: ['attr4'], 57: ['attr4'], 23: ['attr4'], 24: ['attr1', 'attr4'], 25: ['attr4'], 58: ['attr4'], 59: ['attr4'], 29: ['attr4']}

关于python - 将文本元素保存到python中的字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49677047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com