>>> AB
['1', '3', '1', '3']
>>> BC = AB
>>> BC
['1', '3', '1', '3']
>>> BC.sort()
>>> BC
['1', '1', '3', '3']
>>> AB
['1', '1', '3', '3']
我想排序只列出BC。为什么它也排序列表AB以及如何防止它?
答案 0 :(得分:0)
你基本上用AB和BC指向程序内存中的相同区域。因此,要将BC创建为新列表,并将其保存在内存中的其他位置,您可以执行以下操作:
假设这是python:
BC = AB[:] # creates a copy of AB
现在,当你修改BC时,它不会改变AB。这样排序对AB没有影响。现在他们指向记忆中的不同位置。
答案 1 :(得分:0)
BC和AB可能指向到内存中的相同对象,变量持有者AB和BC就像指针 。它们都指向到同一个东西,所以如果你对BC进行排序,BC列表指向进行排序,AB也指向现在排序列出BC。
要更正此问题,您可以说BC = AB[:]
而不是说Unhandled exception in thread started by <function wrapper at 0x1071c11b8>
Traceback (most recent call last):
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in _populate
self.load_app(app_name)
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/Users/shivakrishna/shiva/app/post-web-1.6/modes/directory/models.py", line 24, in <module>
from PIL import Image, ImageDraw, ImageFont
File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/PIL/Image.py", line 67, in <module>
from PIL import _imaging as core
ImportError: dlopen(/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/PIL/_imaging.so, 2): Library not loaded: /opt/local/lib/libjpeg.9.dylib
Referenced from: /Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/PIL/_imaging.so
Reason: image not found
,而不是AB本身,它会在BC中存储AB的副本。这将导致:对一个不的更改反映在另一个