我创建了一个字典,其中的键表示相对距离,值是空列表。我想用嵌套列表中的相对距离值填充这些值——空列表。我的问题是,当我填充字典的值时,它的条目没有按照它们在嵌套列表中出现的顺序填充
这是我最接近解决问题的方法:
relDistDic = { 'a':[], 'b': [] } # dictionary with relative distances
relDist = [[1,2,3], [4,5,6], [7,8,9], [10,11,12] ] #nested list with dstncs
for v in relDistDic.values():
for element in relDist:
if len(v) < 2 :
v.append(element)
我想得到以下输出:
{ 'a':[[1,2,3], [4,5,6]], 'b': [[7,8,9], [10,11,12]] }
但我得到的却是:
{ 'a':[[1,2,3], [4,5,6]], 'b': [[1,2,3], [4,5,6]] }
如有任何帮助或意见,我们将不胜感激,谢谢
关于:
字典乱了!使用而不是插入元素的顺序与迭代时的顺序相同
不仅如此,还有
对于
relDist
中的每个值,您只需要附加前两个值(因为if len(v) < 2
)。也许您是想在追加时从relDist
中删除这些项为此,请使用
pop()
相关问题 更多 >
编程相关推荐