[英]Insert an element into a list in python
I am trying to write a function in python that should take as input 2 arguments as follow f('k', range(4)) and should return the following: 我试图在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']]
I have tried the following but something goes wrong 我尝试了以下方法,但是出了点问题
def f(j,ls):
return [[ls.insert(x,j)]for x in ls]
Does anyone know how to find the solution? 有人知道如何找到解决方案吗?
list.insert()
returns None
because the list is altered in-place. list.insert()
返回None
因为该列表已就地更改。 You also don't want to share the same list object, you'll have to create copies of the list: 您也不想共享相同的列表对象,则必须创建列表的副本 :
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
You also could use slicing to produce new sublists with the extra element 'inserted' through concatenation; 您还可以使用切片来生成带有通过串联“插入”的额外元素的新子列表。 this then gives you one-liner list comprehension:
这样一来,您便可以一目了然地理解清单:
def f(j, ls):
return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]
Demo: 演示:
>>> 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']]
This should work for you. 这应该为您工作。
def f(j,num):
lst=[]
for i in range(num+1):
innerList=list(range(num))
innerList[i:i]=j
lst.append(innerList)
return lst
Demo: 演示:
print f("j",4)
Output: 输出:
[['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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.