我可以使用前置元素而不是附加元素来扩展 Python 中的列表吗? [英] Can I extend list in Python with prepend elements instead of append?

查看:12
本文介绍了我可以使用前置元素而不是附加元素来扩展 Python 中的列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以表演

a = [1,2,3]b = [4,5,6]a.扩展(b)# a 现在是 [1,2,3,4,5,6]

有没有办法执行扩展列表并将新项目添加到列表开头的操作?

像这样

a = [1,2,3]b = [4,5,6]a.某个动作(b)# a 现在是 [4,5,6,1,2,3]

如果重要的话,我使用 2.7.5 版.

解决方案

您可以分配给一个切片:

a[:0] = b

演示:

<预><代码>>>>a = [1,2,3]>>>b = [4,5,6]>>>a[:0] = b>>>一种[4, 5, 6, 1, 2, 3]

本质上,list.extend() 是对 list[len(list):] 切片的赋值.

您可以在任何位置插入"另一个列表,只需在该位置定位空切片:

<预><代码>>>>a = [1,2,3]>>>b = [4,5,6]>>>a[1:1] = b>>>一种[1, 4, 5, 6, 2, 3]

I can perform

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

Is there way to perform an action for extending list and adding new items to the beginning of the list?

Like this

a = [1,2,3]
b = [4,5,6]
a.someaction(b)
# a is now [4,5,6,1,2,3]

I use version 2.7.5, if it is important.

解决方案

You can assign to a slice:

a[:0] = b

Demo:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a[:0] = b
>>> a
[4, 5, 6, 1, 2, 3]

Essentially, list.extend() is an assignment to the list[len(list):] slice.

You can 'insert' another list at any position, just address the empty slice at that location:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a[1:1] = b
>>> a
[1, 4, 5, 6, 2, 3]

这篇关于我可以使用前置元素而不是附加元素来扩展 Python 中的列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆