python删除列表理解中的字典键 [英] python delete dict keys in list comprehension
问题描述
为什么以下旨在删除字典中多个键的表达式无效? (事件
是字典)
Why is the following expression, aiming at deleting multiple keys in a dict, invalid? (event
is a dict)
[del event[key] for key in ['selected','actual','previous','forecast']]
什么
推荐答案
您完全不应该使用列表理解 >强>在这里。列表推导非常适合构建值列表,因此不应将其用于常规循环。使用列表推导来解决副作用是浪费一个完美的列表对象的内存。
You should not use a list comprehension at all here. List comprehensions are great at building a list of values, and should not be used for general looping. Using a list comprehension for the side-effects is a waste of memory on a perfectly good list object.
列表推导也是表达式,因此只能包含其他表达式。 del
是一条语句,不能在表达式内使用。
List comprehensions are also expressions, so can only contain other expressions. del
is a statement and can't be used inside an expression.
只需使用 for
循环:
# use a tuple if you need a literal sequence; stored as a constant
# with the code object for fast loading
for key in ('selected', 'actual', 'previous', 'forecast'):
del event[key]
或使用字典理解力重建字典:
or rebuild the dictionary with a dictionary comprehension:
# Use a set for fast membership testing, also stored as a constant
event = {k: v for k, v in event.items()
if k not in {'selected', 'actual', 'previous', 'forecast'}}
后者会创建一个全新的字典,因此对同一对象的其他现有引用将看不到任何更改。
The latter creates an entirely new dictionary, so other existing references to the same object won't see any changes.
如果必须在表达式中使用键删除,则可以可以使用 object .__ delitem __(key)
,但这不是地方;您最终会得到一个列表,其中包含 None
个对象,并且您会立即丢弃该列表。
If you must use key deletion in an expression, you can use object.__delitem__(key)
, but this is not the place; you'd end up with a list with None
objects as a result, a list you discard immediately.
这篇关于python删除列表理解中的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!