python - 如何以最有效的方式翻转数据集?

标签 python python-3.x algorithm

假设我们有一个像这样的数据集:

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/

相关文章:

python - `del x` 在 Python 中有用吗?

python - Pandas - DF 与列表 - 查找与任何列中的字符串匹配的所有行

python - 如何在 PyQt5 中的外部事件过滤器方法中获取变量值?

numpy - 在 python3.3 上安装 numpy - 为 python3 安装 pip

python - 如何从文本文件中读取和写入整数?

c++ - OpenCV 中 FaceRecognizer 中的 LBP 运算符

algorithm - 在常数时间内找到排序列表中数字的存在? (采访问题)

python - 如何处理拆分中丢失的数据?

python - 如何将 Opencv 集成到 Tkinter 窗口中

python - 使用通过堆栈实现的迭代 DFS 时如何回溯