python给字典分配一个列表会返回空的lis

2024-04-24 15:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我的列表框架链被反映为空([])。frameChain实际上是一个列表,例如:['C Level', 'Medium Term']

jsonOut[x]= {'TEXT' : node.attrib['TEXT'],
             'ID': node.attrib['ID'],
             'Sessions' : frameChain,}

我在我定义的函数之外尝试过这个,它似乎工作得很好。你知道为什么这里会不同吗?你知道吗

x只是一个表示外部字典索引的计数器。你知道吗


Tags: 函数text框架idnode列表字典定义
1条回答
网友
1楼 · 发布于 2024-04-24 15:59:12

根据您的评论,您可能在将列表添加到词典后修改了列表。在python中,几乎所有的东西,例如变量名、列表项、字典项等等,都只引用值,而不包含它们本身。列表是可变的,因此如果您将一个列表添加到字典中,然后通过另一个名称修改列表,那么更改也会显示在字典中。你知道吗

即:

# Both names refer to the same list
a = [1]
b = a    # make B refer to the same list than A
a[0] = 2 # modify the list that both A and B now refer to
print a  # prints: [2]
print b  # prints: [2]

# The value in the dictionary refers to the same list as A
a = [1]
b = {'key': a}
a[0] = 2
print a # prints: [2]
print b # prints: {'key': [2]}

但是,请注意,为变量指定新值不会更改引用的值:

# Names refer to different lists
a = [1]
b = a   # make B refer to the same list than A
a = [2] # make A refer to a new list
print a # prints [2]
print b # prints [1]

您创建了一个新列表,并将项目“手动”从旧列表逐个复制到新列表。这是可行的,但是它占用了很多空间,而且有一种更简单的方法,就是使用切片。切片返回一个新列表,因此如果不指定开始和结束位置,即通过写入list_variable[:],它基本上只返回原始列表的一个副本。你知道吗

即,修改原始示例:

# Names refer to different lists
a = [1]
b = a[:] # make B refer to a copy of the list that A refers to
a[0] = 2
print a  # prints: [2]
print b  # prints: [1]

# The value in the dictionary refers to a different list than A
a = [1]
b = {'key': a[:]}
a[0] = 2
print a # prints: [2]
print b # prints: {'key': [1]}

相关问题 更多 >