Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我想做字典;从二维阵列到二维阵列_Python_Dictionary - Fatal编程技术网

Python 我想做字典;从二维阵列到二维阵列

Python 我想做字典;从二维阵列到二维阵列,python,dictionary,Python,Dictionary,我想从2d数组生成字典和数组 我写代码: data=[[['A','A'],['S','apple'],['W','NY']],[['A','B'],['S','windows'],['W','CF']],[['A','B'],['S','Lenovo'],['W','CH']],[['A','A'],['S','summung'],['W','KL']]] dct = {} ans=[] for i in range(len(data)): for j in range(len(da

我想从2d数组生成字典和数组

我写代码:

data=[[['A','A'],['S','apple'],['W','NY']],[['A','B'],['S','windows'],['W','CF']],[['A','B'],['S','Lenovo'],['W','CH']],[['A','A'],['S','summung'],['W','KL']]]

dct = {}
ans=[]


for i in range(len(data)):
  for j in range(len(data[i])):
    print(j)
    print(data[i][j][0])
    if data[i][j][0] == 'A':
        if data[i][j][0] not in dct:
            dct[data[i][j][0]] = []
        dct[data[i][j][0]].append(data[i][j][2])
        ans.append(data[i][j][1])
    else:
        if data[i][j][0] not in dct:
            dct[data[i][j][0]] = []
        dct[data[i][j][0]].append(data[i][j][2])
        ans.append(data[i][j][1])
但当我运行以下命令时:

dct[data[i][j][0]].append(data[i][j][2])
我得到
索引器

IndexError: list index out of range error
我理想的
dct
输出是

{'A': ['NY', 'KL'], 'B': ['CF', 'CH']}
['apple','summung','windows','Lenovo']
我理想的
ans
输出是

{'A': ['NY', 'KL'], 'B': ['CF', 'CH']}
['apple','summung','windows','Lenovo']

我是一个python初学者,所以我真的不明白怎么了。我应该如何解决这个问题?

对于您要执行的任务,您的逻辑过于复杂。这里有一种使用
collections.defaultdict
的方法,以及一种使用
排序的列表理解方法

该解决方案之所以有效,是因为
排序
是稳定的。因此,您的字典通过简单的迭代和排序将对齐

from collections import defaultdict

d = defaultdict(list)
for i in data:
    d[i[0][1]].append(i[2][1])

ans = [i[1][1] for i in sorted(data, key=lambda x: x[0][1])]
结果

print(d)

defaultdict(list, {'A': ['NY', 'KL'],
                   'B': ['CF', 'CH']})

print(ans)

['apple', 'summung', 'windows', 'Lenovo']

解释输入列表应该变成
{'A':['NY','KL'],'B':['CF','CH']}的规则
我建议您阅读一下如何调试自己的代码。一件有帮助的事情是给变量指定一个重复的表达式,例如
current\u cell=data[i][j][0]
。现在,您可以在任何需要的地方重用此变量名。@RomanPerekhrest dct字典可以使键具有2d数组的第一个数组(如['A'、'A']或['A'、'B'])的第二个元素(表示A或B),值具有2d数组的3st数组(如['W'、'NY']或['W'、'CF']等)第二个要素。你应该学习列表理解和词典理解。使用这些工具,您可能可以更轻松地执行此操作。