我正在考虑从 Matlab 转移到 Python/numpy 进行数据分析和数值模拟。我已经使用 Matlab(和 SML-NJ)多年,并且在没有副作用(禁止 I/O)的功能环境中非常舒适,但对 Python 中的副作用有点不情愿。人们能否分享他们最喜欢的关于副作用的陷阱,如果可能的话,他们是如何解决这些问题的?例如,当我在 Python 中尝试以下代码时,我有点惊讶:
lofls = [[]] * 4 #an accident waiting to happen!
lofls[0].append(7) #not what I was expecting...
print lofls #gives [[7], [7], [7], [7]]
#instead, I should have done this (I think)
lofls = [[] for x in range(4)]
lofls[0].append(7) #only appends to the first list
print lofls #gives [[7], [], [], []]
提前致谢