从一个列表弹出并附加到另一个列表

时间:2017-11-08 21:07:17

标签: python

我想创建三个小列表(每个包含三个元素)和一个包含所有三个列表的大列表。 然后我想从我的第一个列表中弹出最后一个元素并将其附加到第二个列表,并将其作为最后一个元素。

现在,在追加后结果如下:

[“banana”,“apple”] [“”,“”,“”,“lemon”] [“”,“”,“”]

我希望结果看起来像这样:

[“”,“banana”,“apple”] [“”,“”,“lemon”] [“”,“”,“”]

class foodchain:
    temp1 = " "
    temp2 = " "
    temp3 = " "
    first = []
    second = []
    last = []
    biglist = []

    def __init__(self, temp1 = " ", temp2 = " ", temp3 = " "):
        self.temp1 = temp1
        self.temp2 = temp2
        self.temp3 = temp3
        self.first = ["banana", "apple", "lemon"]
        self.second = [self.temp1, self.temp2, self.temp3]
        self.last = [self.temp1, self.temp2, self.temp3]
        self.biglist = [self.first,self.second,self.last]

food = foodchain()

print(food.biglist)

food.biglist[1].append(food.biglist[0].pop())

print(food.biglist)

2 个答案:

答案 0 :(得分:2)

简明扼要地pop从一个列表push到另一个列表:

> list0 = [1, 2, 3]
> list1 = [4, 5, 6]
> list1.append(list0.pop(-1))
> list0
[1, 2]
> list1
[4, 5, 6, 3]

pop()的参数为-1,以获取最后一个元素。

答案 1 :(得分:0)

根据我的评论,我使用来自可爱收藏模块的deque提出了这个解决方案

from collections import deque

class foodchain:
    def __init__(self, temp1=" ", temp2=" ", temp3=" "):
        self.temp1 = temp1
        self.temp2 = temp2
        self.temp3 = temp3
        self.first = deque(["banana", "apple", "lemon"])
        self.second = deque([self.temp1, self.temp2, self.temp3])
        self.last = deque([self.temp1, self.temp2, self.temp3])
        self.big_list = [self.first, self.second, self.last]
    def move21(self):
        self.first.appendleft(self.second.popleft())
        self.second.append(self.first.pop())
food = foodchain()
print(food.big_list)
food.move21()
print(food.big_list)

[deque(['banana', 'apple', 'lemon']), deque([' ', ' ', ' ']), deque([' ', ' ', ' '])]
[deque([' ', 'banana', 'apple']), deque([' ', ' ', 'lemon']), deque([' ', ' ', ' '])]