简体   繁体   English

Python定期从列表中删除项目

[英]Python periodically remove items from a list

Say I have a long list with 1000 elements and I want to periodically delete groups of elements based off of two variables. 假设我的清单很长,包含1000个元素,并且我想根据两个变量定期删除元素组。

So for my_list=[1,2,3,4...1000] , and a=5 , b=7 , I would keep the first 5 elements, delete the next 7, and repeat until the end of the list. 因此,对于my_list=[1,2,3,4...1000]a=5b=7 ,我将保留前5个元素,删除下7个元素,然后重复执行直到列表末尾。

The list will then look like: 列表将如下所示:

my_list = [1,2,3,4,5,12,13,14,15,16...]

I don't know a or b prior to using them, nor the length of the list, so I'm looking for a general solution. 在使用它们之前,我不知道a或b,也不知道列表的长度,因此我正在寻找一种通用的解决方案。

Thanks! 谢谢!

Here's one way to do it using enumerate and taking the mod of the index on the sum of a and b . 这是使用enumerate并以ab的和作为索引的mod的一种方法。 Filter out values whose mod is less than a : 筛选出mod小于a

l = range(1, 30)
a, b = 5, 7
r = [x for i, x in enumerate(l) if i%(a+b) < a]
print(r)
# [1, 2, 3, 4, 5, 13, 14, 15, 16, 17, 25, 26, 27, 28, 29]

PS if you're deleting the next 7, 12 should not be included. PS,如果您要删除下一个7,则不应包含12。

Here's a different approach using iterators: 这是使用迭代器的另一种方法:

import itertools as it

L = list(range(1000))
a, b = 5, 7

mask = it.chain(it.repeat(1, a), it.repeat(0, b))

Result = list(it.compress(L, it.cycle(mask)))

Documentation of the itertools standard module . itertools标准模块的文档

The cool thing here is that no intermediate data is stored in memory, and all the results are generated on-the-fly. 这里很酷的事情是, 没有中间数据存储在内存中,并且所有结果都是即时生成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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