【问题标题】:Python assigning string format return value behavior is inconsistentPython分配字符串格式返回值行为不一致
【发布时间】:2016-03-31 19:00:37
【问题描述】:

在分配像'67.67.%s.%s' % (str(j), str(i))这样的python字符串格式返回值时,分配给dict的key和分配给dict的子dict中的key是不一致的。

例如:

i = 0
j = 1
dict_template = {"id": "1", "another_dict": {"value": "hello"}}
dict_list = []
for idx in list(range(2, 1002)):
    new_dict = copy.copy(dict_template)
    new_dict['id'] = 'obj_id_%s' % str(idx)
    new_dict['another_dict']['value'] = '67.67.%s.%s' % (str(j), str(i))
    dict_list.append(new_dict)
    if i < 254:
        i += 1
    else:
        j += 1
        i = 1

在此示例中,每个 new_dict['another']['value'] 都是相同的字符串并具有相同的 id。 但是,如果我将这一行 new_dict['another_dict']['value'] = '67.67.%s.%s' % (str(j), str(i)) 更改为 new_dict["another_dict"] = '67.67.%s.%s' % (str(j), str(i)),每个 new_dict["another_dict"] 都会有不同的值。

顺便说一句,我使用的是 Python 3.4.3。

【问题讨论】:

    标签: python string python-3.x dictionary


    【解决方案1】:

    copy.copy 执行给定参数的浅拷贝。这意味着它会创建一个新的 dict 并向其添加对第一个 dict 中已经存在的所有内容的引用(而不是副本)。对于字符串和数字等不可变的东西,没有问题。但是每个实例都指向同一个(可变的)内部字典。

    相反,您需要使用copy.deepcopy。它将递归地为模板参数的每个属性创建新副本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2011-09-16
      • 1970-01-01
      • 2018-01-03
      • 2021-02-17
      相关资源
      最近更新 更多