我有一个很大的csv文件,它有3列:
Parent Child Qty
31282 42126A 0.00272
31282 50553 0.107
31282 61119 1
31283 42126A 0.00272
31283 50277 0.107
31283 61119 1
孩子可以是其他孩子的父母。你知道吗
可能有两个相同的孩子有不同的父母,因此数量不同:
31254 31282 0.535
31255 31282 2.8448
我想把它转换成一本字典,包括数量。你知道吗
到目前为止,我可以用以下代码编写dict:
has_parent = set()
all_items = {}
quan = []
for parent, child, qty in data:
if parent not in all_items:
all_items[parent] = {}
if child not in all_items:
all_items[child] = {}
quan.append({'parent': parent,'child': child, 'qty': qty})
all_items[parent][child] = all_items[child]
has_parent.add(child)
result = {}
for key, value in all_items.items():
if key not in has_parent:
result[key] = value
结果dict如下所示:
'31597': {'31598': {'42126A': {},
'50005A': {},
'50365': {},
'50393': {},
'53120': {},
'61554': {}}},
'31599': {'31600': {'50398': {}}},
'31601': {'31602': {'50399': {}}},
'31603': {'31600': {'50398': {}}},
'31604': {'31602': {'50399': {}}},
'31605': {'31606': {'50403': {}}},
'31607': {'31606': {'50403': {}}},
'31609': {'31608': {'51037': {}, '52095': {}, '64041': {}}},
'31612': {'31610': {'40098': {}, '60544': {}, '61501A': {}}},
我的问题是如何将数量插入正确的键中。你知道吗
我可以找到一个密钥的父级,然后查看原始文件并查看数量,但如何在3或4或更多的深度插入该数量?你知道吗
这是子密钥及其多个父密钥的输出。你知道吗
60542
['31280', '31281', '31280', '31281']
----------
61554
['31596', '31598', '31280', '31281', '31280', '31281']
您需要一个辅助数据结构来跟踪与要修改的叶相对应的根节点。一个简单的选择是adjacency list。这样您就可以知道从哪个节点开始搜索。你知道吗
或者(以更简单的方式),您可以实现BFS/DFS,但是数据中缺少结构将确保时间复杂性较差。你知道吗
相关问题 更多 >
编程相关推荐