Python:通过删除第n个元素从现有列表构建新列表 [英] Python: building new list from existing by dropping every n-th element
问题描述
我想建立一个新列表,其中初始列表的第n个元素都被忽略了,例如:
I want to build up a new list in which every n-th element of an initial list is left out, e.g.:
之所以使用['second', 'third', 'fifth', 'sixth'
是因为n = 3
该怎么做?
首先,通过建立新列表而不是尝试删除列表来完成此操作是否正确?对于后者,我尝试使用deque
和rotate
,但最终陷入混乱.
为了建立一个新列表,我尝试使用range(1,len(list),n)
进行操作,但这是要删除的元素位置,而不是要为新列表保留的元素位置.
How to do that?
Is it - first of all - correct to accomplish this by building up a new list, instead of trying to delete? For the latter I tried with deque
and rotate
but that ended up in confusion.
To build up a new list I was trying something with range(1,len(list),n)
but that are the element positions to be deleted and not the ones which are to be kept for the new list.
如何获取所需列表?
推荐答案
>>> [s for (i,s) in enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']) if i%3]
['second', 'third', 'fifth', 'sixth']
答案分几个步骤:
enumerate
函数提供一个元组列表,其索引后面是项目:
The enumerate
function gives a list of tuples with the index followed by the item:
>>> list(enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']))
[(0, 'first'), (1, 'second'), (2, 'third'), (3, 'fourth'), (4, 'fifth'), (5, 'sixth'), (6, 'seventh')]
然后检查索引是否不被三除,如果是,则包括该项.
then you check if the index does not divide by three, and if so you include the item.
这篇关于Python:通过删除第n个元素从现有列表构建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!