Python 您能否提供编写以下代码的不可理解的方法
输出是Python 您能否提供编写以下代码的不可理解的方法,python,python-3.x,dictionary,dictionary-comprehension,Python,Python 3.x,Dictionary,Dictionary Comprehension,输出是 d = {'a':1,'b':2,'c':3,'d':4} d = { k + 'c' : v * 2 for k : v in d.items() if v > 2} 本词典理解相当于: { 'cc': 6 , 'dc': 8} 输出: # Set up a new dictionary to hold the result d_new = {} # Iterate over key/value pairs for k, v in d.items(): # If th
d = {'a':1,'b':2,'c':3,'d':4}
d = { k + 'c' : v * 2 for k : v in d.items() if v > 2}
本词典理解相当于:
{ 'cc': 6 , 'dc': 8}
输出:
# Set up a new dictionary to hold the result
d_new = {}
# Iterate over key/value pairs
for k, v in d.items():
# If the value is greater than 2
if v > 2:
# Append to the new dictionary as required.
d_new[k + 'c'] = v*2
理解很容易转化为常规代码(反之亦然)。您可以使用以下方法就地执行此操作:
d={'a':1,'b':2,'c':3,'d':4}
对于列表中的k(d.keys()):
v=d.pop(k)
如果v>2:
d[k+'c']=v*2
印刷品(d)
给出:
>>> d_new
{'cc': 6, 'dc': 8}
{'cc': 6, 'dc': 8}