Reputation: 10895
I'm not sure if this has been asked before as it seems to be a simple question, I tried to search it but did not find a very good answer.
Say I have a list of numbers a
. I know I can get out every fifth number by a[::5]
.
What should be the simplest way to get the rest of the list (items in a
but not in a[::5]
)?
Edit:
this is not the same question as Finding elements not in a list as I already know that the rest of the list consists of a[1::5]+a[2::5]+a[3::5]+a[4::5]
, I'm just asking is there a simpler way / syntax sugar for that?
Edit:
Thank you all for answering.
Is there a solution without scanning over the whole list?
Upvotes: 0
Views: 75
Reputation: 5238
[x for i, x in enumerate(a) if i % 5 != 0]
not in set(a[::5])
will not work correctly when list contains equal elements. not in a[::5]
is also not optimal from performance point of view.
Edit There is no syntactic sugar for your problem in Python. Take a look at numpy: it has extensive slicing possibilities.
Edit To avoid list scanning, you could create wrapper class with __getitem__
method.
Upvotes: 2
Reputation: 3415
This would do it, without any index look up overheads.
result = [n for i,n in enumerate(a) if i % 5 != 0]
Upvotes: 0
Reputation: 5867
I would start by something like:
[v for v in a if v not in a[::5]]
Store the unwanted value in a set
before could lead to better perf, because not in
method is in O(1)
for sets:
unwanted = set(a[::5])
[v for v in a if v not in unwanted]
If the amount of data is huge, bloom filter could be a good substitute.
Upvotes: 2
Reputation: 2073
You can try this:
[a[i-1] for i in range(1, len(a) + 1) if i % 5]
Basically, it checks for every position to see if it is a multiple of 5 or not. You don't have to create a set object this way.
Upvotes: 0
Reputation: 3525
Does this help you?
items = [1,2,3,4]
Z = [3,4,5,6]
a = list(set(items)-set(Z))
# a =[1, 2]
Such as:
fifths = a[::5]
not_fifths = list(set(a)-set(fifths))
Upvotes: 0