这个条件可以缩短吗

  • 本文关键字:条件 python
  • 更新时间 :
  • 英文 :


是否可以只使用字典中的.get()函数?这是我们能做的最好的缩短这段代码的方法吗?

n_dictDict类型(大写D(,NES只是str的列表

eted_info = {}
for key in n_dict:
if key in NES:
eted_info[key] = n_dict[key]

我只是想知道是否有一种更好/更像Python的方法来检索值,就像C#使用TryGetValue一样。

我认为字典理解和使用n_dict.items()是完成的最干净的方法

n_dict = {'a': 1, 'b': 2, 'c': 3}
NES = ['a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
eted_info = {key:value for key,value in n_dict.items() if key in NES}
print(eted_info)

结果

{'a': 1, 'c': 3}

你可以用字典理解做一些事情,比如:

eted_info = {key: n_dict[key] for key in n_dict if key in NES}

如果您想避免对NES中的每个项对n_dict中的每个项目进行迭代的O(n^2(操作,您可以构建一个密钥列表作为set交集,并对其进行迭代:

eted_info = {k: n_dict[k] for k in set(n_dict) & set(NES)}

NES中的键上迭代;使用默认为Nonen_dict.get.get;有条件地添加到CCD_ 15。

for key in NES:
v = n_dict.get(key,None)
if v: eted_info[key] = v
  • 无论n_dict的长度如何,这只会在列表上迭代一次
  • 假设n_dict中的所有值都是真实的。其他占位符可用于默认值

最新更新