gpt4 book ai didi

Python:创建一个新字典,从嵌套列表的字典中获取值

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:43 25 4
gpt4 key购买 nike

我是 Python 和一般编程新手,在为我的代码找到正确的语法方面遇到一些困难。

我有两个列表:

I = [0, 1]
A = ['a', 'b']

假设有一本像这样的字典:

my_dictionary = {(0, 'a'): [[0, 4, 0, 0, 3, 0, 0], [4, 0, 0, 3, 0, 0, 0]], (0, 'b'): [[2, 0, 2, 0, 2, 1, 0], [2, 0, 2, 1, 0, 2, 0]], (1, 'a'): [[0, 0, 0, 7, 0, 0, 0], [0, 0, 0, 0, 0, 7, 0], [0, 0, 7, 0, 0, 0, 0]], (1, 'b'): [[2, 0, 2, 0, 2, 1, 0], [2, 0, 2, 1, 0, 2, 0]]}

我想创建一个像这样的新字典: new_dictionary = {(0, 'a', 0, 0) : 0, (0, 'a', 0, 1) : 4, .... (1 , 'b', 0, 0) : 2, ..... }

new_dictionary = dict()
for i in I:
for j in A:
for c in my_dictionary[i, j]:
for d in c:
new_dictionary.update(map((i, j, c, d), my_dictionary[i, j][c][d]))

这返回我类型错误:列表索引必须是整数,而不是列表

非常感谢您的帮助。预先感谢您!

最佳答案

这里的问题是,您使用列表 c 作为 my_dictionary[i, j], my_dictionary[i, j] 的索引code> 将返回列表索引的列表,列表索引应始终为整数

让我解释一下你是如何登陆这里的

for i in I

将返回I列表中的元素0和1

for j in A

将返回A列表中的元素,即'a'和'b'

for c in my_dictionary[i, j]

将从对应于my_dictionary[i, j]的列表列表中返回元素,就像my_dictionary[0, 'a']它将返回[0 , 4, 0, 0, 3, 0, 0] 和 [4, 0, 0, 3, 0, 0, 0] 所以 c 将被分配一个列表,所以当你会写这个 my_dictionary[i, j][c] 这将返回一个错误 TypeError: listindexs must be integers, not list 因为 c 是一个不能的列表此处用于列表 my_dictionary[i, j]

的索引

关于Python:创建一个新字典,从嵌套列表的字典中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com