Let's say I have the following list
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
I want to find all possible sublists of a certain lenght where they don't contain one certain number and without losing the order of the numbers.
For example all possible sublists with length 6 without the 12 are:
[1,2,3,4,5,6]
[2,3,4,5,6,7]
[3,4,5,6,7,8]
[4,5,6,7,8,9]
[5,6,7,8,9,10]
[6,7,8,9,10,11]
[13,14,15,16,17,18]
The problem is that I want to do it in a very big list and I want the most quick way.
Update with my method:
oldlist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
newlist = []
length = 6
exclude = 12
for i in oldlist:
if length+i>len(oldlist):
break
else:
mylist.append(oldlist[i:(i+length)]
for i in newlist:
if exclude in i:
newlist.remove(i)
I know it's not the best method, that's why I need a better one.
A straightforward, non-optimized solution would be
result = [sublist for sublist in
(lst[x:x+size] for x in range(len(lst) - size + 1))
if item not in sublist
]
An optimized version:
result = []
start = 0
while start < len(lst):
try:
end = lst.index(item, start + 1)
except ValueError:
end = len(lst)
result.extend(lst[x+start:x+start+size] for x in range(end - start - size + 1))
start = end + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With