将ord中嵌套列表中的元素附加到列表字典

2024-10-02 20:43:21 发布

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

我创建了一个字典,其中的键表示相对距离,值是空列表。我想用嵌套列表中的相对距离值填充这些值——空列表。我的问题是,当我填充字典的值时,它的条目没有按照它们在嵌套列表中出现的顺序填充

这是我最接近解决问题的方法:

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]] }

如有任何帮助或意见,我们将不胜感激,谢谢


Tags: 方法in距离列表fordictionary字典顺序
2条回答

关于:

relDist = [[1,2,3], [4,5,6], [7,8,9], [10,11,12] ] #nested list with dstncs

relDistDic = { 'a': relDist[:2], 'b': relDist[2:] } # dictionary with relative distances

字典乱了!使用而不是插入元素的顺序与迭代时的顺序相同

不仅如此,还有

for v in relDistDic.values():
  for element in relDist:
    if len(v) < 2:
      v.append(element)

对于relDist中的每个值,您只需要附加前两个值(因为if len(v) < 2)。也许您是想在追加时从relDist中删除这些项

为此,请使用pop()

for v in relDistDic.values():
  for i in range(2):
    if len(relDist) > 0:
      v.append(relDist.pop(0))

相关问题 更多 >