在python中使用map的不一致

时间:2017-07-17 13:54:00

标签: python

我有一个常量文件constants.py,如下所示:

querystring = {
    "limit":"10000",
    "sort":"desc"
}

dummy1 = {
    "a": "22",
    "q": "*",
}

dummy2 = {
    "a": "24",
    "q": "**",
}

streams = [dummy1, dummy2]

我试图通过操纵constants.py文件中的值来初始化列表。

from constants import querystring, streams
def setParams(dummy, querystring):
    ld = {}
    ld["query"] = setQuerystring( dummy, querystring)
    print ld
    return ld

def setQuerystring( dummy, querystring):
    query = querystring
    query["filter"] = "stream:" + dummy["a"]
    query["query"] = dummy["q"]
    return query

l = map(lambda x: setParams(x, querystring), streams)
print l[0]
print l[1]

当lambda函数正在运行时,输出被正确打印,但是当我看到地图返回的最终值时,值是不同的。为何这种不一致?

节目输出:

{'query': {'sort': 'desc', 'filter': 'stream:22', 'limit': '10000', 'query': '*'}} # l[0] -> during lambda execution
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}} # l[1] -> during lambda execution
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}} # l[0] -> from map 
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}} # l[1] -> from map

1 个答案:

答案 0 :(得分:3)

您在迭代中重用和修改querystring dict。因此,后续迭代的后续更改将传播到先前附加的副本。您应该考虑将副本附加到每个dict,然后修改该副本:

def setQuerystring( dummy, querystring):
    query = querystring.copy()
    ...
{'query': {'sort': 'desc', 'filter': 'stream:22', 'limit': '10000', 'query': '*'}}
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}}
{'query': {'sort': 'desc', 'filter': 'stream:22', 'limit': '10000', 'query': '*'}}
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}}