将obj插入列表一次

时间:2014-11-15 14:50:39

标签: 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 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的情况下仅将其插入一次?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

问题是你期望Python通过值传递,但Python总是引用。考虑这个SO帖子:Emulating pass-by-value...

您可以在前几行创建一个副本:

from copy import deepcopy
def print_database(seats_plan):
    seats_plan_copy = deepcopy(seats_plan)
相关问题