我可以在Python中同时在同一个项目上使用.pop()和.append()吗?

ema*_*nim 2 python append

所以我有两个列表,我想使用.pop()从ListA中删除一个项目,然后使用.append()将它添加到ListB.我试过这个,但是一旦我使用.pop(),.append()函数就会占用一个索引.

这是我到目前为止的代码:

ListA = ['a', 'b', 'c', 'd', 'e']
ListB = []

ListA.pop()
ListA.pop()
ListA.pop()

print 'ListA =', ListA
print 'ListB =', ListB
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

ListA = ['a', 'b']
ListB = []
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像这样:

ListA = ['a', 'b']
ListB = ['e', 'd', 'c']
Run Code Online (Sandbox Code Playgroud)

我知道我没有任何.append()函数,但当我把它们放在那里时我得到一个错误.这就是代码只使用.pop()函数.我想使用.pop()删除正在删除的项目,然后将其附加到ListB.

谢谢你的帮助.

Hun*_*len 7

将弹出元素传递给append函数:

a= ['a', 'b', 'c', 'd', 'e']
b= []

b.append(a.pop())
b.append(a.pop())
b.append(a.pop())

print 'ListA =', a
print 'ListB =', b



Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> a = ['a','b','c']
>>> b = []
>>> b.append(a.pop())
>>> b.append(a.pop())
>>> b.append(a.pop())
>>> print "a =", a
a = []
>>> print "b =", b
b = ['c', 'b', 'a']
>>>
Run Code Online (Sandbox Code Playgroud)