简体   繁体   English

将 Python 列表列表转换为字典的幼稚方法

[英]Naive approach to convert a Python list of lists to a dictionary

Suppose I have a list like this lst = [[0,1,5,0], [4,0,0,7], [0,11]] .假设我有一个这样的列表lst = [[0,1,5,0], [4,0,0,7], [0,11]] I want to create a dictionary, where the key is a tuple (i, j) and the value is lst[i][j] .我想创建一个字典,其中键是一个元组(i, j) ,值是lst[i][j] It should show something like this d = {(0,0): 0, (0, 1): 1, (0,2): 5, (0,3): 0 ... (2,1): 11} I believe you got the pattern now.它应该显示如下d = {(0,0): 0, (0, 1): 1, (0,2): 5, (0,3): 0 ... (2,1): 11}我相信你现在得到的格局。 My attempt to produce something like this goes as fellows:我试图产生这样的东西作为研究员:

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

Which doesn't work.哪个不起作用。 It doesn't sweep through the whole list.它没有扫过整个列表。 Kindly help me find the problem with my humble code.请帮助我找到我不起眼的代码的问题。

Your code in question is almost correct, take a look at the code below, which makes a slight adjustment:你有问题的代码几乎是正确的,看看下面的代码,它做了一些细微的调整:

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))

When run this outputs:运行此输出时:

{(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}

The answer from @hitter is probably the easiest to understand. @hitter 的回答可能是最容易理解的。 As an alternative you can use 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}

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

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