如何根据计数删除嵌套列表中的列表


import time
dc = []
def u():
for i in range(10):
if i < 5:
dc.append([i])
print(dc)
time.sleep(10)
while True:
u()

第一次运行后输出:[[0], [1], [2], [3], [4]]

第二次运行后输出:[[0], [1], [2], [3], [4], [0], [1], [2], [3], [4]]

第三次运行的输出:

[[0], [1], [2], [3], [4], [0], [1], [2], [3], [4], [0], [1], [2], [3], [4], [0], [1], [2], [3], [4]]

第4次运行的输出:

[[0], [1], [2], [3], [4], [0], [1], [2], [3], [4], [0], [1], [2], [3], [4], [0], [1], [2], [3], [4], [0], [1], [2], [3], [4]]

我想在5个循环后删除第一次迭代中的值,并保留第二组值,直到它达到5个循环。

我该怎么做?

一种方法是跟踪插入的每个列表的长度,然后删除该数字。此外,您的数据毫无意义,因为每个项目都在自己的列表中,这是毫无意义的。

x = [0], [1], [2], [3], [4]
y = [0], [1], [2], [3], [4]
dc = []
itemLengths = []
dc.extend(x)
itemLengths.append(len(x))
dc.extend(y)
itemLengths.append(len(y))
print(dc)
print(dc[itemLengths.pop(0):])

或者更好的处理方法:

class U:
def __init__(self):
self.dc = []
self.insertLength = []
def add(self, data):
self.dc.extend(data)
self.insertLength.append(len(data))
self.remove()
return self
def remove(self):
if len(self.insertLength) == 6:
self.dc = self.dc[self.insertLength.pop(0):]
return self
def wait(self, timer):
time.sleep(10)
u = U()
u.add(x)
u.add(y)
u.add(x)
u.add(x)
u.add(x)
u.add(x)
print(u.insertLength)
print(len(u.insertLength))
print(u.dc)

最新更新