您能否提供编写下面的代码的不理解的方法

问题描述 投票:-1回答:2
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}
python-3.x dictionary dictionary-comprehension
2个回答
0
投票

此字典理解等效于:

# 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
投票

理解很简单,可以转换为常规代码(反之亦然)。您可以使用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}
© www.soinside.com 2019 - 2024. All rights reserved.