[英]Nested Dictionary Comprehension from a List of Lists in Python 3
edgeList是列表的列表
我有這個工作,但它比我想要的慢:
for rowIndex, rowVal in enumerate(edgeList):
for colIndex, colVal in enumerate(rowVal):
EdgeDict[rowIndex][colIndex] = colVal
使用dict理解會更快嗎? 我試過了,但是語法糾結了
這樣的理解應該可以做到,但是我懷疑它的速度要快得多。 此外,值的訪問與您擁有的列表中的訪問相同:
edge_dict = {row: dict(enumerate(row_val)) for row, row_val in enumerate(edgeList)}
這樣做幾乎沒有意義。 您已經有了從坐標對到值的映射 。 您的edgeList
是該地圖:
edgeList[integer_value_for_row][integer_value_for_col]
映射到您的價值觀。
您可以使用以下方法制作字典:
{row_index: dict(enumerate(row)) for row_index, row in enumerate(edgeList)}
這將映射的結果enumerate()
直接向字典; 無需嵌套該循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.