我试图在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]有谁知道如何找到解决方案?
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:
[['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()返回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']]list.insert() returns None because the list is altered in-place. 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 outputYou 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']]更多推荐
发布评论