【问题标题】:Naive approach to convert a Python list of lists to a dictionary将 Python 列表转换为字典的简单方法
【发布时间】:2020-03-08 10:01:43
【问题描述】:

假设我有一个类似lst = [[0,1,5,0], [4,0,0,7], [0,11]] 的列表。 我想创建一个字典,其中键是元组(i, j),值是lst[i][j]。它应该显示类似 d = {(0,0): 0, (0, 1): 1, (0,2): 5, (0,3): 0 ... (2,1): 11} 的内容,我相信您现在已经掌握了模式。我尝试制作这样的东西是作为研究员:

def convert(lst):
    d = dict()
    for i in range(len(lst)):
        for j in range(i):
            d(i, j)] = lst[i][j]
    return d

这不起作用。它没有扫过整个列表。请帮我用我简陋的代码找出问题所在。

【问题讨论】:

  • 第二个 for 循环应该会抛出错误,导致您的代码无法运行。

标签: python list dictionary matrix


【解决方案1】:

您的问题代码几乎是正确的,请看下面的代码,稍作调整:

def convert(lst):
    d = {}
    for i in range(len(lst)):
        for j in range(len(lst[i])): # This is the part that differentiates.
            d[(i, j)] = lst[i][j]
    return d

lst = [[0,1,5,0], [4,0,0,7], [0,11]]
print(convert(lst))

运行此输出时:

{(0, 0): 0, (0, 1): 1, (0, 2): 5, (0, 3): 0, (1, 0): 4, (1, 1): 0, (1, 2): 0, (1, 3): 7, (2,0): 0, (2, 1): 11}

【讨论】:

    【解决方案2】:

    @hitter 的回答可能是最容易理解的。作为替代方案,您可以使用dictionary comprehensions。

    >>> lst = [[0,1,5,0],[4,0,0,7],[0,11]]
    >>> {(i, j): lst[i][j] for i in range(len(lst)) for j in range(len(lst[i]))}
    {(0, 0): 0, (0, 1): 1, (0, 2): 5, (0, 3): 0, (1, 0): 4, (1, 1): 0, (1, 2): 0, (1, 3): 7, (2, 0): 0, (2, 1): 11}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-21
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2019-02-10
      • 1970-01-01
      • 2015-11-14
      相关资源
      最近更新 更多