简体   繁体   English

按顺序附加到嵌套列表中的列表元素字典

[英]Appending to a dictionary of lists elements from a nested list in order

I've created a dictionary with keys that represent relative distances and values that are empty lists. 我创建了一个字典,其中的键代表相对距离和值为空列表。 I would like to populate these values--empty lists--with entries from a nested list that are the values of the relative distances. 我想用嵌套列表中的相对距离值填充这些值-空列表。 My problem is that when I populate the values of the dictionary, its entries are not being filled in the order in which they appear in the nested list. 我的问题是,当我填充字典的值时,它的条目没有按照它们在嵌套列表中出现的顺序填充。

This is the closest I've gotten to solving the problem: 这是我最接近解决问题的方法:

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)

I would like to get the following output: 我想得到以下输出:

{ 'a':[[1,2,3], [4,5,6]], 'b': [[7,8,9], [10,11,12]] }

But instead I am getting this: 但是相反,我得到这个:

{ 'a':[[1,2,3], [4,5,6]], 'b': [[1,2,3], [4,5,6]] }

Any help or comments are greatly appreciated, thanks! 任何帮助或评论都将不胜感激,谢谢!

Dictionaries are unordered! 字典是无序的! The order that you insert elements with not be the same order that they appear as when you iterate through them. 您插入用一样的显示顺序,当你遍历它们作为元素的顺序。

Not only that, but in 不仅如此,

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

For each value in relDist , you're only appending the first two (because of if len(v) < 2 ). 对于relDist每个值,您只需追加前两个值(因为if len(v) < 2 )。 Perhaps you meant to remove the items from relDist as you append them? 也许您打算在添加它们时从relDist删除它们?

To do so, use pop() . 为此,请使用pop()

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

What about: 关于什么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM