简体   繁体   English

从Python 3列表中的嵌套字典理解

[英]Nested Dictionary Comprehension from a List of Lists in Python 3

edgeList is a list of lists edgeList是列表的列表

I have this working but its slower than I want: 我有这个工作,但它比我想要的慢:

for rowIndex, rowVal in enumerate(edgeList):
    for colIndex, colVal in enumerate(rowVal):
        EdgeDict[rowIndex][colIndex] = colVal

Would it be faster using dict comprehension? 使用dict理解会更快吗? I tried, but got tangled up in the syntax 我试过了,但是语法纠结了

A comprehension like this should do it, but I doubt that it is significantly faster. 这样的理解应该可以做到,但是我怀疑它的速度要快得多。 Also, the accessing of values is the same as in the list you have: 此外,值的访问与您拥有的列表中的访问相同:

edge_dict = {row: dict(enumerate(row_val)) for row, row_val in enumerate(edgeList)}

There is very little point in doing this. 这样做几乎没有意义。 You already have a map from coordinate pair to value . 已经有了从坐标对到值的映射 Your edgeList is that map: 您的edgeList是该地图:

edgeList[integer_value_for_row][integer_value_for_col]

maps to your values. 映射到您的价值观。

You can produce your dictionary with: 您可以使用以下方法制作字典:

{row_index: dict(enumerate(row)) for row_index, row in enumerate(edgeList)}

This maps the result of enumerate() directly to a dictionary; 这将映射的结果enumerate()直接向字典; there is no need to nest that loop. 无需嵌套该循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM