在Python中的2D列表中插入值
我正在寻找一种在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'] ]
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,#’)