我有一个列表,如下所示:
voting_records = [['1.', 'DIRECTOR', 'Management'],
['1', 'Allison Grant Williams', 'For'],
['2', 'Sheila Hartnett-Devlin', 'For'],
['3', 'James Jessee', 'For'],
['4', 'Teresa Polley', 'For'],
['5', 'Ashley T. Rabun', 'For'],
['6', 'James E. Ross', 'For'],
['7', 'Rory Tobin', 'For']]
我使用列表解析创建了一个名为voting_records_short
的列表副本:
cnames = ["Record","Proposal","Sponsor","VoteCast"]
voting_records_short = [record for record in voting_records if len(record) < len(cnames)]
然后我创建了一个voting_records_short
的切片并将其保存在directors
中。然后我在for循环中修改directors
列表,如下所示:
if len(voting_records_short) == 0: pass
else:
ifdirector = ["DIRECTOR" in record for record in voting_records_short]
if True in ifdirector:
directorindx = int(ifdirector.index(True))
directorline = [voting_records_short[directorindx]]
directors = voting_records_short[directorindx+1:]
sponsoridx = cnames.index("Sponsor")
for ls in range(len(directors)):
directors[ls][0] = directorline[0][0] + directors[ls][0]
directors[ls][1] = directorline[0][1] + " " +directors[ls][1]
directors[ls].insert(sponsoridx,directorline[0][-1])
为什么在for循环中修改控制器列表会同时修改voting_records_short
列表和voting_records
,如以下输出所示:
In [2]: voting_records
Out[2]:
[['1.', 'DIRECTOR', 'Management'],
['1.1', 'DIRECTOR Allison Grant Williams', 'Management', 'For'],
['1.2', 'DIRECTOR Sheila Hartnett-Devlin', 'Management', 'For'],
['1.3', 'DIRECTOR James Jessee', 'Management', 'For'],
['1.4', 'DIRECTOR Teresa Polley', 'Management', 'For'],
['1.5', 'DIRECTOR Ashley T. Rabun', 'Management', 'For'],
['1.6', 'DIRECTOR James E. Ross', 'Management', 'For'],
['1.7', 'DIRECTOR Rory Tobin', 'Management', 'For']]
In [9]: voting_records_short
Out[9]:
[['1.', 'DIRECTOR', 'Management'],
['1.1', 'DIRECTOR Allison Grant Williams', 'Management', 'For'],
['1.2', 'DIRECTOR Sheila Hartnett-Devlin', 'Management', 'For'],
['1.3', 'DIRECTOR James Jessee', 'Management', 'For'],
['1.4', 'DIRECTOR Teresa Polley', 'Management', 'For'],
['1.5', 'DIRECTOR Ashley T. Rabun', 'Management', 'For'],
['1.6', 'DIRECTOR James E. Ross', 'Management', 'For'],
['1.7', 'DIRECTOR Rory Tobin', 'Management', 'For']]
我以为只有directors
列表会被修改(也许还有voting_records_short
,但我不确定),但为什么原始的voting_records
列表被修改了?
1条答案
按热度按时间sbtkgmzw1#
您正在迭代原始voting_records并将对每个记录的引用存储在新列表中;因此,对带有引用的记录所做的更改将同时修改两个列表--如上所述:深拷贝
运行代码后: