1

I have a python list in which i need to do takewhile. I am getting output as

['fd', 'dfdf', 'keyword', 'ssd', 'sdsd'] but I need to get ['3=', 'fd', 'dfdf', 'keyword', 'ssd', 'sdsd', ';']

 from itertools import takewhile, chain

l = [1, 2, "3=", "fd", "dfdf", "keyword", "ssd", "sdsd", ";", "dds"]

s = "keyword"

# get all elements on the right of s
right = takewhile(lambda x: ';' not in x, l[l.index(s) + 1:])

# get all elements on the left of s using a reversed sublist
left = takewhile(lambda x: '=' not in x, l[l.index(s)::-1])

# reverse the left list back and join it to the right list
subl = list(chain(list(left)[::-1], right))

print(subl)
# ['fd', 'dfdf', 'keyword', 'ssd', 'sdsd']
qwww
  • 1,313
  • 4
  • 22
  • 48

1 Answers1

1

the problem with takewhile is to get the element that satisfies the condition.

you could try this (if i understood your question correctly)

l = [1, 2, "3=",  "fd", "dfdf", "keyword", "ssd", "sdsd", ";", "dds"]

it = iter(l)

first_index = next(i for i, item in enumerate(it) 
                   if isinstance(item, str) and '=' in item)
last_index = next(i for i, item in enumerate(it, start=first_index+1) 
                  if isinstance(item, str) and ';' in item)

print(l[first_index:last_index + 1])

this creates an iterator it (so that the items that have been checked against the fist condition will not be checked again).

the rest should be pretty straightforward.

this answer might also be helpful.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111