如何将一个列表的内容插入另一个列表

编程入门 行业动态 更新时间:2024-10-17 00:22:35
本文介绍了如何将一个列表的内容插入另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图合并两个列表的内容,以便以后对整个数据集执行处理.我最初看了内置的insert函数,但它是作为列表而不是列表的内容插入的.

I am trying to combine the contents of two lists, in order to later perform processing on the entire data set. I initially looked at the built in insert function, but it inserts as a list, rather than the contents of the list.

我可以切片并追加列表,但是有没有比这更干净/更Python化的方式来做我想做的事情:

I can slice and append the lists, but is there a cleaner / more Pythonic way of doing what I want than this:

array = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] addition = ['quick', 'brown'] array = array[:1] + addition + array[1:]

推荐答案

您可以使用作业左侧的slice语法执行以下操作:

You can do the following using the slice syntax on the left hand side of an assignment:

>>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog'] >>> array[1:1] = ['quick', 'brown'] >>> array ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

这与Pythonic差不多!

That's about as Pythonic as it gets!

更多推荐

如何将一个列表的内容插入另一个列表

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

发布评论

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

>www.elefans.com

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