coefficients = {} coefficients_keys = [] for k in range(0, len(compound_middle)): coefficients_keys.append(compound_middle[k][0]) coefficients = {}.fromkeys(coefficients_keys, {})#这里默认给每个键创建为{}空字典 for i in range(0, len(compound_middle)): j = 0 while j < len(compoundlist) + 1:#在这里赋值给空字典时,其他所有键的{}都同时被赋值了 if j == 0: coefficients[compound_middle[i][0]][j] = compound.get(compound_middle[i][0], 0) else: coefficients[compound_middle[i][0]][j] = compoundlist_c[j - 1].get(compound_middle[i][0], 0) j += 1 #图片里面我在第一个if j == 0时,本意是只赋一个值给'Cu',但是print之后发现,其他键也被赋予了相同的值,然而我并没有去操作, 所以以后在使用{}.fromkeys要注意
Python利用{}.fromkeys来创建空字典的时候要注意附默认值时其他键会同时变化
最新推荐文章于 2021-09-06 09:25:18 发布