【问题标题】:Difference between dict[item].append(word) and dict[item] + [word]dict[item].append(word) 和 dict[item] + [word] 的区别
【发布时间】:2016-07-22 14:09:45
【问题描述】:

我的字典结构是:

 key             val
 item         a list of values

我是如何发起我的dict:

dict[item] = [word]
type(dict[item]) ---> gives me list

当进入循环并尝试使用相同的键向列表添加更多值时,dict[item].append(word) 给了我None 而dict[item] + [word] 有效

为什么会这样?

【问题讨论】:

标签: python dictionary syntax


【解决方案1】:
  • 代码dict[item].append(word)对dict[item]处的列表进行变异,函数append的返回值为None。
  • 代码dict[item] + [word] 不会改变dict[item] 处的列表,而只是计算两个列表的串联。

这相当于:

arr = [1]
res = arr + [2]
assert res == [1, 2]
assert arr == [1]
res = arr.append(2)
assert res is None
assert arr == [1, 2]

对于问题中的示例,append 的等效代码是:

dict[item] += [word]

【讨论】:

    【解决方案2】:

    使用 .append()

    d = {'example': ['string']}
    d['example'].append('test') # mutates the list
    print d
    >> {'example': ['string','test']}
    

    使用 list + list

    d = {'example': ['string']}
    d['example'] + ['test'] # return {'example':['string', 'test]} but no mutation
    print d
    >> {'example': ['string']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2012-04-21
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      相关资源
      最近更新 更多