Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elegant way to filter list

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'"]
like image 784
user765443 Avatar asked Oct 21 '13 11:10

user765443


2 Answers

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.

like image 125
TerryA Avatar answered Nov 05 '22 17:11

TerryA


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']
like image 21
Inbar Rose Avatar answered Nov 05 '22 18:11

Inbar Rose