Reputation: 1892
I have two list like following way.I need to extract value from after = i.e. xyz and .81. I am trying to make one general solution for both list or make for future also. As of now, I was doing join and find int the list than split. But I feel it can be done in better way.
a = ['.TITLE', "'=", 'xyz', 'vdd', '=', '0.81', 'temp', "-40'"]
b = ['.TITLE', "'$", 'abc', '=', 'xyz', 'vdd', '=', '0.99', 'temp', "125'"]
Upvotes: 5
Views: 137
Reputation: 5092
A non elegant way would be to use flags :
a = ['.TITLE', "=", 'xyz', 'vdd', '=', '0.81', 'temp', "-40'"]
b = ['.TITLE', "'$", 'abc', '=', 'xyz', 'vdd', '=', '0.99', 'temp', "125'"]
def extract(L,sep="="):
pick_this_one = False
for item in L :
if pick_this_one:
pick_this_one = False
yield item
if item == sep :
pick_this_one = True
for value in extract(a+b):
print value
>>> xyz
0.81
xyz
0.99
>>>
Upvotes: 0
Reputation: 43437
As a function:
import itertools
def extract_items_after(lst, marker='='):
for x, y in itertools.izip_longest(lst, lst[1:]):
if marker in x:
yield y
Using your data:
a = ['.TITLE', "'=", 'xyz', 'vdd', '=', '0.81', 'temp', "-40'"]
b = ['.TITLE', "'$", 'abc', '=', 'xyz', 'vdd', '=', '0.99', 'temp', "125'"]
for l in [a, b]:
print list(extract_items_after(l))
Results:
>>>
['xyz', '0.81']
['xyz', '0.99']
Upvotes: 4
Reputation: 59974
You could use next()
with a generator:
a = ['.TITLE', "'=", 'xyz', 'vdd', '=', '0.81', 'temp', "-40'"]
a1 = iter(a)
for item in a1:
if '=' in item:
print next(a1)
Prints:
xyz
0.81
Note that if =
is the last item, this will raise a StopIteration
error.
You could also use enumerate()
:
a = ['.TITLE', "'=", 'xyz', 'vdd', '=', '0.81', 'temp', "-40'"]
for i, j in enumerate(a):
if '=' in j:
print a[i+1]
Prints:
xyz
0.81
Once again this will raise an error (IndexError
) if =
is the last item.
Upvotes: 6