简体   繁体   中英

Can I use .pop() and .append() on the same item at the same time in Python?

So I have two lists and I want to use .pop() to remove an item from ListA and then use .append() to add it to ListB. I've tried this, but as soon as I use .pop(), the .append() function takes one index after that.

Here is the code I have so far:

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

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

print 'ListA =', ListA
print 'ListB =', ListB

The output I get is:

ListA = ['a', 'b']
ListB = []

I would like the output to look like this:

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

I know I don't have any .append() functions, but when I put them in there I get an error. So that's the code working with just the .pop() function. I want to take the item that is being removed with .pop() and then append it to ListB.

Thanks for your help.

Pass the popped element to the append function:

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']
>>>

我不明白你的问题,因为你没有显示你想要的输出,但我想你想要的是这个?

ListB.append(ListA.pop())

why don't you try:

b.append(a[-1]) a.pop()

b.append(a[-1]) a.pop()

b.append(a[-1]) a.pop()

I think this is as simple as:

a = ListA.pop()
a1 = ListA.pop()

 ListB.append(a)
 ListB.append(a1)

or I'm one line.

ListB.append(ListA.pop())
b.append(a.pop())
b.append(a.pop())
b.append(a.pop())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM