Python 将obj插入列表一次
我编写了一个函数,该函数应该在表中插入一个2D列表 代码如下:Python 将obj插入列表一次,python,multidimensional-array,Python,Multidimensional Array,我编写了一个函数,该函数应该在表中插入一个2D列表 代码如下: seats_plan = [[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]] def print_database(seats_plan): for row
seats_plan = [[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]]
def print_database(seats_plan):
for row in seats_plan:
row.insert(0, seats_plan.index(row))
seats_plan.insert(0, [' ', '0', '1', '2', '3', '4'])
for k in seats_plan:
for char in k:
if char is True:
print '.',
elif char is False:
print 'x',
else:
print char,
print
输出为:
0 1 2 3 4
0 . . . . .
1 . . . . .
2 . . . . .
3 . . . . .
4 . . . . .
但是它也改变了seats\u plan
,因此如果我再次调用该函数,它会再次插入数字。
如何让它只插入一次,而不更改原始的
seats\u计划
?问题在于您期望Python按值传递,但Python总是引用。考虑一下这样的帖子:
您可以使用以下方法在前几行中创建副本:
from copy import deepcopy
def print_database(seats_plan):
seats_plan_copy = deepcopy(seats_plan)
不要更改列表,因为它只是一个参考,例如与原始列表相同。在需要时打印数字:
seats_plan = [[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]]
def print_database(seats_plan):
print ' ', '0', '1', '2', '3', '4'
for row, seats in enumerate(seats_plan):
print row,
for seat in seats:
print '.' if seat else 'x',
print
或者有列表理解能力
def print_database(seats_plan):
plan = [ '%d %s' % (row, ' '.join('.' if seat else 'x' for seat in seats))
for row, seats in enumerate(seats_plan)]
plan.insert(0, ' ' + ' '.join(str(c) for c in range(len(seats))))
print '\n'.join(plan)
您应该创建列表的副本并对其进行修改,而不是对原始列表进行修改。您想要一个函数,在第一次调用时将内容插入到表中,但在第二次调用时不会插入内容?需要明确的是,Python传递引用,这与“按引用传递”不同,它允许函数在调用方的命名空间中重新分配名称。@NedBatchelder,我按您所述编辑了答案。