python - 所有键的字典值都会自动删除
问题描述
代码
def fill_dictionary_with_valid_addr_row_data( df ):
data_list = []
dictionary = {}
int_endianness = 0
for i in df.index:
addrstr = str(df['Address'][i])
if (addrstr != 'nan'):
try:
addr = int(addrstr, 16)
except:
print("Address in excel is not in hex format : %s", addrstr)
sys.exit()
width = int(df['Width'][i])
width = int(width / 8);
endianess = df['Endianess'][i]
if (endianess != 'B') and (endianess != 'L'):
print("ERROR: Register endianess is not B or L");
print("Register : %x, Endianess : %s" % (addr, endianess))
sys.exit()
if endianess == 'B':
int_endianness = 1
data_list.append(addr)
data_list.append(width)
data_list.append(int_endianness)
dictionary[i] = data_list
print(dictionary)
data_list.clear()
print(dictionary)
return dictionary
问题
当我在 for 循环中打印字典时,一切都很好。当我在 for 循环外打印字典时,所有值(列表)都是空的。
以下是日志
{0: [22216704, 4, 1]}
{0: [22216716, 4, 1], 5: [22216716, 4, 1]}
{0: [22216720, 4, 1], 5: [22216720, 4, 1], 7: [22216720, 4, 1]}
{0: [], 5: [], 38: [], 7: []}
我是一个初学者的python程序员。我试图通过互联网搜索很多,但我没有找到任何解决方案。
有什么线索吗?
解决方案
每当您这样做dictionary[i] = data_list
时,您实际上都会将列表的引用分配给字典条目。考虑以下示例:
>>> l = [1,2,3]
>>> d = {}
>>> d["a"] = l
>>> d["b"] = l
>>> d
{'a': [1, 2, 3], 'b': [1, 2, 3]}
>>> l.clear()
>>> d
{'a': [], 'b': []}
如您所见,更改l
会反映在所有字典值中。您每次在打印输出中看到的是相同的列表分别分配给一个、两个或三个字典条目。因为它总是相同的值,看起来好像您每次都添加了不同的列表,但事实并非如此。
您真正想要做的是为每个循环迭代创建一个新列表:
for i in df.index:
...
data_list = []
data_list.append(addr)
data_list.append(width)
data_list.append(int_endianness)
dictionary[i] = data_list
或更短:
dictionary[i] = [addr, width, int_endianness]
使用此代码data_list
将在每次迭代中包含一个新列表,与之前定义的列表无关。
推荐阅读
- asp.net - 带有 ASP.NET Core WebAPI 的 Dart 中的令牌刷新并发问题
- powershell - PowerShell 中的竞争条件
- angularjs - 如何在 Ionic 3 中控制台记录来自 JSON 对象的单个值
- python - 从 2 类 softmax 输出中获取单值预测
- sparql - SPARQL - 如何计算特定主题的 wiki PageOutDegree?
- node.js - GroupBy 日期 + MongoDB
- assembly - 如何在mips中动态分配内存并打印起始地址
- java - Angularjs如何仅在调用init方法后加载div内容
- c++ - 给出奇数输出的简单 C++ 计算
- python - 在 GUI 中显示函数