gpt4 book ai didi

python - 将 Python 列表转换为字典的简单方法

转载 作者:行者123 更新时间:2023-12-02 07:26:20 25 4
gpt4 key购买 nike

假设我有一个像这样的列表 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

这不起作用。它并没有横扫整个列表。请帮助我用我的简陋代码找到问题。

最佳答案

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

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}

关于python - 将 Python 列表转换为字典的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60586354/

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