2014-11-15 33 views
-2

我写了一个函数,该函数应该将2D列表插入表中。将obj插入列表中一次

这是代码:

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_plan,所以如果我再次调用该函数再次插入数字。 如何在不更改原来的seats_plan的情况下只插入一次?

+0

您应该创建一个副本* *列表和修改,而不是原来的。 – jonrsharpe

+0

你想要一个函数在第一次被调用时将事物插入表中,但不是第二次? –

回答

0

问题是你期待Python传递值,但Python总是引用。考虑这个SO职位:Emulating pass-by-value...

你可以在你的第一个几行创建一个副本:

from copy import deepcopy 
def print_database(seats_plan): 
    seats_plan_copy = deepcopy(seats_plan) 
+2

为了清楚起见,Python传递了引用,它与“通过引用传递”不同,后者允许函数在调用者的名称空间中重新分配名称。 –

+0

@NedBatchelder,我编辑了你所描述的答案。 –

1

不要更改列表,因为它仅仅是一个参考,例如与原始列表相同。打印的数字,在需要的时候:

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)