英文:
combining two dict_key instances with preserving their order
问题
我有两个具有不同键的字典。我想将这两个键组合成一个列表或其他东西,以便我可以进行迭代。但是顺序很重要,因为在脚本的某些地方,我需要通过enumerate()
保留顺序进行其他计算。
这是我试图做的一个小例子:
ns.keys()
Out[1]: dict_keys([108])
no.keys()
Out[2]: dict_keys([120, 124, 126, 127, 112, 114, 115, 117, 118, 135, 132, 133, 109, 130, 111, 129, 136])
我想要像下面这样同时迭代它们:
for key in [ns.keys() | no.keys()]:
print(key)
Out[3]: {129, 130, 132, 133, 135, 136, 108, 109, 111, 112, 114, 115, 117, 118, 120, 124, 126, 127}
顺序很重要,因为我还想做以下操作:
for i, key in enumerate([ns.keys() | no.keys()]):
print(i, key)
我希望[ns.keys() | no.keys()]
的顺序首先是ns.keys()
,然后是no.keys()
。在这个示例中,它应该是:
[108, 120, 124, 126, 127, 112, 114, 115, 117, 118, 135, 132, 133, 109, 130, 111, 129, 136]
以下方法可行:list(ns.keys()) + list(no.keys())
,还有其他方法吗?
英文:
I have two dict with different keys. I would like to combine both keys into a list or something so that I can iterate over. However the order is important because at some places of the script I need to preserve the order for other calculations via enumerate()
Here is a small example of what I am trying to do:
ns.keys()
Out[1]: dict_keys([108])
no.keys()
Out[2]: dict_keys([120, 124, 126, 127, 112, 114, 115, 117, 118, 135, 132, 133, 109, 130, 111, 129, 136])
I want to iterate over both of them like following:
for key in [ns.keys() | no.keys()]:
print(key)
Out[3]: {129, 130, 132, 133, 135, 136, 108, 109, 111, 112, 114, 115, 117, 118, 120, 124, 126, 127}
The order is important because, I also want to do following:
for i, key in enumerate([ns.keys() | no.keys()]):
print(i, key)
I want the order of [ns.keys() | no.keys()]
to be first ns.keys()
then no.keys()
. In this example, it should be:
[108, 120, 124, 126, 127, 112, 114, 115, 117, 118, 135, 132, 133, 109, 130, 111, 129, 136]
Following works list(ns.keys()) + list(no.keys())
, any other idea?
答案1
得分: 1
[*ns.keys(), *no.keys()]
:
解压列表中的字典键以进行迭代。
英文:
Just unpack dict keys within a list for iteration:
[*ns.keys(), *no.keys()]
答案2
得分: 1
你可以使用链:
from itertools import chain
a = {"a": 2}
b = {"b": 2, "c": 3}
for i, key in enumerate(chain(a, b)):
print(i, key)
# 0 a
# 1 b
# 2 c
如果你的字典很大,这是一种节省内存的方式。
英文:
You can use chain:
from itertools import chain
a = {"a": 2}
b = {"b": 2, "c": 3}
for i, key in enumerate(chain(a, b)):
print(i, key)
# 0 a
# 1 b
# 2 c
This is a memory-efficient way of doing, if your dicts are large.
答案3
得分: 0
不需要使用keys()方法。枚举或解包字典会直接返回键:
for i, key in enumerate([*ns, *no]):
print(i, key)
英文:
You dont' event need to use the keys() method. enumerating or unpacking dictionaries returns the keys directly:
for i,key in enumerate([*ns,*no]):
print(i,key)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论