python - 创建列表列表并添加到 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)和字典键的值。
解决方案
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]]}
推荐阅读
- android - 使用播放控制台进行内部测试,我如何取消发布应用程序
- wordpress-theming - 子主题:修改文件
- sql - 我应该避免在 mybatis 的查询映射器中测试条件吗?
- javascript - 使用单个搜索按钮和清除按钮搜索数据表
- python-3.x - 当 nparray 大小低于内存限制时,为什么 numpy.astype 会引发内存错误?
- javascript - 如何在 twilio 中更好地控制出站消息?
- java - 尝试使用 Cordova 构建一个 android 应用程序
- ios - 如何将自定义字典数组传递给 Swift 中的请求正文?
- c# - 如何编译这个 github 项目?
- r - 使用 if else 语句添加列