在python中将元素插入到列表中(Insert an element into a list in python)

编程入门 行业动态 更新时间:2024-10-28 16:18:07
在python中将元素插入到列表中(Insert an element into a list in python) python

我试图在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 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']]

更多推荐

本文发布于:2023-07-07 15:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1065222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   元素   列表中   python   element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!