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}
守候你守候我
浏览 101回答 2
2回答
慕桂英4014372
理解转换为常规代码非常简单(反之亦然)。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 * 2print(d)给出:{'cc': 6, 'dc': 8}
这个字典理解等价于:# Set up a new dictionary to hold the resultd_new = {}# Iterate over key/value pairsfor 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}