您能否提供不理解的方式来编写以下代码

时间:2020-01-22 13:49:21

标签: python python-3.x dictionary dictionary-comprehension

[TestFixture]
public class ImmutableTest
{
    [Test]
    public void Test()
    {
        var m = new Immutable("usd", "us");
        string s = m.Currency;
        Assert.AreEqual("usd", s);
    }
}

输出为

d = {'a':1,'b':2,'c':3,'d':4}
d = { k + 'c' : v * 2 for k : v in d.items() if v > 2}

2 个答案:

答案 0 :(得分: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}

答案 1 :(得分: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}