首页 > 解决方案 > 创建列表列表并添加到 for 循环中的字典

问题描述

我想创建一个循环来为每个键生成一个字典,其中每个键有 5 个列表,每三个值。并根据字典的键和列表的索引添加编辑列表 2 和 3 的最后一个值(所以列表 2 和 3)。

我尝试了以下代码,但收到错误消息:'cannot unpack non-iterable int object'

# Create dicitonairy with 6 empty lists
dict_of_lists = dict.fromkeys(range(0,6),[])
for key, value in dict_of_lists:
    # Create 5 lists with the list number as the first value
    for li in range(5):
        dict_of_lists[key] = [li,0,0]
    # Edit the last value of list 1 and 2 (index)
    for wi in [1,2]:
        dict_of_lists[wi][2] = item[wi]*price[key]

创建以下输出的最佳方法是什么:

{
0:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
1:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
2:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
3:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
4:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
5:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
}

其中 x 是基于它所在的列表(1 到 5)和字典键的值。

标签: pythonlistdictionaryfor-loop

解决方案


dict_of_lists = dict.fromkeys(range(0,6),[])
for key, value in dict_of_lists.items():
    # Create 5 lists with the list number as the first value
    l = []
    for li in range(5):
        if li == 1 or li == 2:
            # l.append([li, 0, li*key]) 
            l.append([li, 0, 'x'])
        else:
            l.append([li,0,0])
    dict_of_lists[key] = l
print (dict_of_lists)

输出:

{0: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
1: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
2: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
3: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
4: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
5: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]]}

推荐阅读