dict.fromkeys(SetA,...)中的列表理解 [英] List Comprehension in a dict.fromkeys(SetA, ...)

查看:82
本文介绍了dict.fromkeys(SetA,...)中的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用现有信息生成一个新字典.使用dict.fromkeys()传递参数,例如DictA.keys()set()DictA.values(),但是,这就是我要坚持的:

I want to generate a new dictionary using pre-existing information. Using dict.fromkeys() passing arguments such as a set() of DictA.keys() and the DictA.values(), but, here's what I'm stuck in:

NewDictFromKeys = dict.fromkeys(set(DictA.keys()), DictA.values())

但是传递DictA.values()是逻辑,它将返回以下内容:

But passing DictA.values() is logic that it will return this:

{'pnrdshfxgjltmqacbvuek': [10, 5, 14, 9, 7, 6, 1, 2, 4, 8, 12, 11, 13, 3],   'prktahjvqcgfsbuxdlemn': [10, 5, 14, 9, 7, 6, 1, 2, 4, 8, 12, 11, 13, 3], ...
 ... }

以此类推.

问题是:为每个键分配一个与其自身相对应的值.我提到列表理解是因为它可能是一个很好的解决方案,但是如何应用是另一个问题.

The problem is: Assigning for each key a value that corresponds to itself. I mentioned List Comprehension because it might be one good solution, but how to apply is another problem.

推荐答案

这是因为dict.fromkeys()将第二个参数重用于所有值.您一遍又一遍地存储了相同列表作为参考.

That's because dict.fromkeys() reuses the second argument for all values. You stored the same list as a reference over and over again.

请改用dict理解:

{k: DictA.values() for k in DictA}

对dict理解中的左侧键和值表达式是针对每个迭代执行的.每次再次调用DictA.values()时,都会产生一个新的列表对象.

The left-hand side key and value expressions in a dict comprehension are executed for every iteration. Each time DictA.values() is called again, producing a new list object.

请注意,这里不需要调用set(DictA),您可以为所有键直接在DictA 上进行迭代,并且它们已经是唯一的(必须).

Note that there is no need to call set(DictA) here, you can iterate over DictA directly for all the keys, and they are already unique (they have to be).

这篇关于dict.fromkeys(SetA,...)中的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆