Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中的2D列表中插入值_Python_List_Insert - Fatal编程技术网

在Python中的2D列表中插入值

在Python中的2D列表中插入值,python,list,insert,Python,List,Insert,我正在寻找一种在Python中向2D列表插入值的方法。我的样本清单如下: List= [ ['A', 'B'], ['C', 'D'] ] def Foo(l): rows = len(l) cols = len(l[0]) for row in xrange(rows): l.insert(row, '#') 我希望在列表中每个列表的开头插入一个值,使其看起来像这样: List = [ ['#','A', 'B'], ['#','C', 'D'] ]

我正在寻找一种在Python中向2D列表插入值的方法。我的样本清单如下:

List= [ ['A', 'B'], ['C', 'D'] ]
def Foo(l):
    rows = len(l)
    cols = len(l[0])
    for row in xrange(rows):
        l.insert(row, '#')
我希望在列表中每个列表的开头插入一个值,使其看起来像这样:

List = [ ['#','A', 'B'], ['#','C', 'D'] ]
我编写了一个函数,如下所示:

List= [ ['A', 'B'], ['C', 'D'] ]
def Foo(l):
    rows = len(l)
    cols = len(l[0])
    for row in xrange(rows):
        l.insert(row, '#')
但这给了我以下输出:

List= [ '#', '#', ['A', 'B'], ['C', 'D'] ]
当您执行
l.insert()
时,它会将一个项目添加到
l
而不是子列表中,以迭代子列表,您可以执行以下操作:

for row in l:
    row.insert(0,"#")
或使用
xrange

for i in xrange(len(l)):
    l[i].insert(0,"#")
当您执行
l.insert()
时,它会将一个项目添加到
l
而不是子列表中,以迭代子列表,您可以执行以下操作:

for row in l:
    row.insert(0,"#")
或使用
xrange

for i in xrange(len(l)):
    l[i].insert(0,"#")

用于l:row中的行。插入(0,#’)
用于l:row中的行。插入(0,#’)