我正在尝试在python中编写一个函数,该函数应该作为输入2参数,如f('k',range(4))并且应该返回以下内容:
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
我尝试了以下但出了点问题
def f(j,ls):
return [[ls.insert(x,j)]for x in ls]
有谁知道如何找到解决方案?
答案 0 :(得分:2)
list.insert()
会返回None
,因为列表会就地更改。您也不想共享相同的列表对象,您必须创建列表的副本:
def f(j, ls):
output = [ls[:] for _ in xrange(len(ls) + 1)]
for i, sublist in enumerate(output):
output[i].insert(i, j)
return output
您还可以使用切片来生成新的子列表,并通过串联“插入”额外的元素;然后,这给你一个列表理解:
def f(j, ls):
return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]
演示:
>>> def f(j, ls):
... output = [ls[:] for _ in xrange(len(ls) + 1)]
... for i, sublist in enumerate(output):
... output[i].insert(i, j)
... return output
...
>>> f('k', range(4))
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
>>> def f(j, ls):
... return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]
...
>>> f('k', range(4))
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]
答案 1 :(得分:0)
这应该适合你。
def f(j,num):
lst=[]
for i in range(num+1):
innerList=list(range(num))
innerList[i:i]=j
lst.append(innerList)
return lst
演示:
print f("j",4)
输出:
[['k', 0, 1, 2, 3], [0, 'k', 1, 2, 3], [0, 1, 'k', 2, 3], [0, 1, 2, 'k', 3], [0, 1, 2, 3, 'k']]