简体   繁体   English

在Python 3中定期选择列表元素

[英]Selecting List Elements Periodically in Python 3

Say I have a list 说我有一个清单

Q = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

I believe I can extract the first and every ninth value thereafter using the extended slice notation: 我相信我可以使用扩展切片表示法提取第一个和第九个值:

Q[::9]

Which should give: 哪个应该给:

[0,9,18]

But how can I similarly select all the elements apart from those? 但是,我如何才能类似地选择这些元素之外的所有元素?

You mean this? 你是这个意思?

>>> lis =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> lis[1::9]
[1, 10]

Extended slice notations: 扩展切片符号:

lis[start : stop : step]  #default values : start = 0, stop = len(lis), step = 1

You can pass your own value for start (by default 0 be used) 您可以传递自己的start值(默认情况下,使用0)

Update: 更新:

>>> lis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> se = set(range(0, len(lis),9))   #use a list if the lis is not huge.
>>> [x for i,x in enumerate(lis) if i not in se]
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17]

#for your example even this will work:
>>> [x for i,x in enumerate(lis) if i%9 != 0]
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17]

In case you have not repeated numbers, this is a general solution for any collection of numbers (not necessarily consecutive): 如果您没有重复的数字,这是任何数字集合(不一定是连续的)的通用解决方案:

>>> Q = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> list(set(Q).difference(Q[::9]))
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17]
>>> 

It uses set.difference s to get the set that is the difference between the original list and the sublist to be removed. 它使用set.difference来获取set ,该set是原始列表和要删除的子列表之间的差异。

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

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