我正在改变for循环中的状态字典,并在每次迭代时将新状态附加到列表中.
在Python中,字典当然是可变的,因此附加到列表中的是对连续变异字典对象的引用.所以最后我得到一个相同重复引用的列表,指向状态的最终版本.
state = {'temp': 21.6, 'wind': 44.0}
state_list = []
for i in range(10):
state['temp'] += 0.5
state['wind'] -= 0.5
state_list.append(state)
Run Code Online (Sandbox Code Playgroud)
有没有办法告诉翻译我希望"通过价值传递"?我能够在追加前的行中构造一个元组或一些可变的元素,并在列表中附加说明元组.我只是想检查这是最好的解决方案.
来自R,我天真地尝试过
dfE_fitted['E_after'] = dfE_fitted['E_before']
Run Code Online (Sandbox Code Playgroud)
那给了我
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
Run Code Online (Sandbox Code Playgroud)
很公平,我会尝试那样:
dfE_fitted.loc[:,'E_after'] = dfE_fitted['E_before']
Run Code Online (Sandbox Code Playgroud)
这给了我
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/indexing.py:337: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[key] = _infer_fill_value(value)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/indexing.py:517: SettingWithCopyWarning:
A value is trying to be set on a copy of a …Run Code Online (Sandbox Code Playgroud) 阅读了一些地方(包括这里)之后:Understanding dict.copy() - 浅还是深?
它声称 dict.copy 将创建一个浅拷贝,也称为对相同值的引用。但是,当我自己在 python3 repl 中使用它时,我只能按值获得副本?
a = {'one': 1, 'two': 2, 'three': 3}
b = a.copy()
print(a is b) # False
print(a == b) # True
a['one'] = 5
print(a) # {'one': 5, 'two': 2, 'three': 3}
print(b) # {'one': 1, 'two': 2, 'three': 3}
Run Code Online (Sandbox Code Playgroud)
这是否意味着浅拷贝和深拷贝不一定会影响不可变值?
请问python中这两个代码有什么区别:
white=[2,4,8,9]
black = white
Run Code Online (Sandbox Code Playgroud)
和
white=[2,4,8,9]
black = white[:]
Run Code Online (Sandbox Code Playgroud)
非常感谢.
为什么在Python中,使用n*[dict()]来创建嵌套字典导致相同的字典对象?
>>> d = [(111, 2222), (3333, 4444), (555, 666)]
>>> d
[(111, 2222), (3333, 4444), (555, 666)]
>>> x = len(d) * [dict().copy()][:]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x # All entries of x gets modified
[{'x': 'u'}, {'x': 'u'}, {'x': 'u'}]
>>>
>>> x = [dict(), dict(), dict()]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x # only one entry of x gets modified
[{'x': 'u'}, {}, {}]
>>>
Run Code Online (Sandbox Code Playgroud)