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}
2 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
理解转换为常规代码非常简单(反之亦然)。pop您可以使用以下方法就地执行此操作:
d = {'a':1,'b':2,'c':3,'d':4}
for k in list(d.keys()):
v = d.pop(k)
if v > 2:
d[k + 'c'] = v * 2
print(d)
给出:
{'cc': 6, 'dc': 8}
猛跑小猪
TA贡献1858条经验 获得超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_new
{'cc': 6, 'dc': 8}
添加回答
举报
0/150
提交
取消