从一个列表中弹出并附加到其他列表

2024-04-19 15:07:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在,附加后的结果如下所示:

[“香蕉”,“苹果”][“,”“,”“,”“柠檬”][“,”“,”“,”“]

我希望结果如下:

[“”,“香蕉”,“苹果”][“”,“”,“柠檬”][“”,“”,“”]

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)

Tags: self苹果元素列表foodfirstlastsecond
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来获取最后一个元素。你知道吗

基于我的评论,我建议使用可爱的集合模块中的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([' ', ' ', ' '])]

相关问题 更多 >