简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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