简体   繁体   English

如何将嵌套列表转换成字典

[英]How to convert a nested list into a dictionary

I am supposed to convert a nested list into a dictionary. 我应该将嵌套列表转换成字典。 If I have the list: 如果我有清单:

data=[[['1','2','-2'], ['3','-1','4']]

I want it to become: 我希望它成为:

d={(0, 0): 1, (0, 1): 3, (1, 0): 2, (1, 1): -1, (2, 0): -2, (2, 1): 4}

The tricky part is I you need to see this list as a matrix: 棘手的部分是我需要以矩阵形式查看此列表:

'1','2','-2'
'3','-1','4'
  • Note:Keys in d are not those values' position in that list. 注意:d中的键不是该值在该列表中的位置。 keys should be positions of values in that matrix. 键应该是该矩阵中值的位置。 For example, the key of '3' is (0,1) while the position of '3' in the list is [1][0]. 例如,键“ 3”为(0,1),而列表中“ 3”的位置为[1] [0]。 (0,1) should be column o and row 1 in that matrix(I understand it in this way) (0,1)应该是该矩阵的o列和第1行(我以这种方式理解)

So the keys in the dictionary should be their position in that matrix. 因此,字典中的键应该是它们在该矩阵中的位置。 I am confused and I tried: 我很困惑,我尝试过:

for m in range(len(data)):
    for n in range(len(data[m])):
        d[(m,n)]= data[n][m]

I know it's wrong because it will become out of range. 我知道这是错误的,因为它将超出范围。 I am so struggling with it. 我很努力。

像这样的东西:

data_field = {(i,j): item  for i, lst in enumerate(data) for j,item in enumerate(lst)}

Your current data is invalid syntax, however, I believe this is what you are looking for: 您当前的data语法无效,但是,我认为这是您要查找的内容:

data= [['1','2','-2'], ['3','-1','4']]
new_result = {(a, i):data[i][a] for i in range(len(data)) for a in range(len(data[0]))}

Output: 输出:

{(0, 1): '3', (0, 0): '1', (2, 1): '4', (2, 0): '-2', (1, 0): '2', (1, 1): '-1'}

I believe your list of lists already represents what you want, just a bit inverted. 我相信您的清单清单已经代表了您想要的清单,只是有点倒了。 You say you want to do matrix[(2,1)] to get 4 . 您说您想做matrix[(2,1)]得到4 Is it really so hard to do data[1][2] instead? 代替data[1][2]真的那么难吗? But since you regard the inversion as indispensable, you can convert the list of lists this way. 但是由于您认为倒置是必不可少的,因此可以通过这种方式转换列表列表。

>>> data=[['1','2','-2'], ['3','-1','4']]  # I corrected your mismatched parens
>>> matrix={}
>>> for x, a in enumerate(zip(*data)):
        for y, b in enumerate(a):
            matrix[(x,y)] = int(b)
>>> matrix
{(0, 0): 1, (0, 1): 3, (1, 0): 2, (1, 1): -1, (2, 0): -2, (2, 1): 4}
>>> matrix[(2,1)]
4

A more readable way to do this would be to write a function to do the inversion, instead of reorganizing the data: 一种更易读的方法是编写一个函数来进行求逆,而不是重新组织数据:

>>> def matrix(coords):
        y, x = coords
        return int (data[x][y])
>>> matrix((2,1))
4 

I personally think that long comprehensions look unintuitive, so: 我个人认为,长时间的理解似乎很不直观,因此:

for y, rows in enumerate(data):
    for x, col in enumerate(rows):
        d[(x,y)] = col

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

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