[英]How to do this list/dict comprehension in python
I am creating a python dictionary as follows: 我正在创建如下的python字典:
d= {i : chr(65+i) for i in range(4)}
Now output of d
is {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
现在d
输出为{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
I have an list of keys that I want to look up as follows: 我有一个要查找的键列表,如下所示:
l = [0, 1]
Now what I want to do is create another list which contains the values corresponding to these keys and I wanted to know if there was a pythonic way to do so using list or dict comprehensions. 现在,我要做的是创建另一个列表,其中包含与这些键对应的值,并且我想知道是否存在使用列表或字典理解的Python方式。
I can do something as follows: 我可以做如下事情:
[x for x in d[0]]
However, I do not know how to iterate over the entries of my list in this setting. 但是,我不知道如何在此设置中遍历列表中的条目。 I tried: 我试过了:
[x for x in d[a] for a in l] # name 'a' not defined
[x for x in d[for a in l]] # invalid syntax
You want to iterate over l
, so use for element in l
. 您想遍历l
,因此可for element in l
。 Then look stuff up in your dictionary in the left-hand side, in the value-producing expression: 然后在左侧字典中的值产生表达式中查找内容:
[d[element] for element in l]
Note that a dictionary mapping consecutive integers starting at 0 to letters isn't all that efficient; 注意,将连续的从0开始的整数映射到字母的字典效率不高。 you may as well make it a list: 您也可以将其列出:
num_to_letter = [chr(65 + i) for i in range(4)]
This still maps 0
to 'A'
, 1
to 'B'
, etc, but without a hashing step. 这仍然将0
映射到'A'
,将1
映射到'B'
等,但是没有哈希步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.