0

I'm trying to return specific items in a list based on a pattern.

If the the value '04' appears and the value immediately after it is '01', then return the next 3 values after, but not '04' or '01'. If '04' appears and '01' is not after, then it can be ignored entirely

list = ['04','01','dd','dd','8a','04','2e', '04','01','dd','dd','8a']

for i in list:
    if '04' in list and list.index('04')+1 == '01':
        new_list = list.index('04')+2
        print (new_list) 

I tried following the likes of Finding the index of an item in a list, but I couldn't adapt it to my problem.

EDIT:

The list is far longer (3000+ elements), and I need to return the next 172 elements after '04' and '01', not 3. Shouldn't have used that as an example. Apologies!

yatu
  • 86,083
  • 12
  • 84
  • 139
red_sach
  • 47
  • 1
  • 8

2 Answers2

1

Here's one way using generators:

from itertools import islice

l = ['04','01','dd','dd','8a','04','2e', '04','01','dd','dd','8a']

next_n = 3
l_i = iter(l)
out = []
for i in l_i:
    if i=='04':
        if next(l_i)=='01':
            out.append(list(islice(l_i, 0, next_n)))

print(out)
# [['dd', 'dd', '8a'], ['dd', 'dd', '8a']]
yatu
  • 86,083
  • 12
  • 84
  • 139
  • +1. This will handle OP's requirement of *"next 172"* which he edited lately. Not sure how he would want to handle overlapping cases though. – Austin Jun 23 '20 at 14:02
  • thx. Yeh, probably not worth trying to guess on how that should be handled though, not mentioned in the question either @austin – yatu Jun 23 '20 at 14:04
0

Hi i figured out a way with the enumerate function:

lst = ['04','01','dd','dd','8a','04','2e', '04','01','dd','dd','8a']
n_elements = 172
result = []
for idx, item in enumerate(lst):
    if item == '04' and lst[idx+1] == '01' and (idx< len(lst) - n_elements):
        result.append(lst[idx+2:idx+2+n_elements ])

print(result)

Out[1]: [['dd', 'dd', '8a'], ['dd', 'dd', '8a']]

Let me know if it suits you :)

SaulVP
  • 90
  • 6