Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 您能否提供编写以下代码的不可理解的方法_Python_Python 3.x_Dictionary_Dictionary Comprehension - Fatal编程技术网

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}