Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to get a value from a list element

Tags:

python

list

I have a list of lines from a parsed log like so:

parsedLog = ['20151005 09:11:14 LOG_ID 00000000', '20151005 09:11:14 LOG_ADDR 0173acc4\n    Address of log', '20151005 09:11:14 READ_CONFIG 00000105',

I am looking for the cleanest way to extract the value 0173acc4 from the second element in the list based off a the string LOG_ADDR (i.e. the key) (reason being is the log will not always be consistent).

I currently am using the following one liner:

filter(lambda line: 'LOG_ADDR' in line, parsedLog)[0].split('\n')[-8:]
like image 555
ILostMySpoon Avatar asked Mar 14 '23 14:03

ILostMySpoon


1 Answers

You may use regex.

for line in parsedlog:
    if 'LOG_ADDR' in line:
        print re.search(r'\S+(?=\n)', line).group()

\S+ matches one or more non-space characters. So this \S+(?=\n) would match one or more non-space characters only if it's followed by a newline character. Lookaheads are assertions which won't consume any single char but asserts whether a match is possible or not.

or

Change the print stmt to,

print re.search(r'\bLOG_ADDR\s+(\S+)', line).group(1)

or

>>> for line in parsedLog:
    if 'LOG_ADDR' in line:
        s = line.split()
        for i,j in enumerate(s):
            if j == 'LOG_ADDR':
                print(s[i+1])


0173acc4
>>> 

or

>>> for line in parsedLog:
    if 'LOG_ADDR' in line:
        s = line.split()
        print s[s.index('LOG_ADDR')+1]


0173acc4
like image 68
Avinash Raj Avatar answered Mar 26 '23 21:03

Avinash Raj