假设我们有一个像这样的数据集:
a: 1,2,3,5,6
b: 4,1,2
c: 1,4
现在我们要将此数据集转换为:
1: a,b,c
2: a,b
3: a
4: b,c
5: a
6: a
这个转换可以通过字典来完成,但是有没有办法更有效地做到这一点
目前我是这样做的:
uFile = open("t/u.txt","r")
uDic = dict()
for cnt1, line in enumerate(uFile):
lineAr = line.strip().split(' ')
for item in lineAr:
if item not in uDic.keys():
uDic[item] = []
uDic[item].append(cnt1)
然后保存输出。
最佳答案
为此使用 defaultdict:
from collections import defaultdict
d = {'a': [1, 2, 3, 5, 6], 'b': [4, 1, 2], 'c': [1, 4]}
o = defaultdict(list)
for k, v in d.items():
for vv in v:
o[vv].append(k)
print(dict(o))
{1: ['a', 'b', 'c'],
2: ['a', 'b'],
3: ['a'],
5: ['a'],
6: ['a'],
4: ['b', 'c']}
关于python - 如何以最有效的方式翻转数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55096252/