The cleanest way to get a value from a list item

I have a list of lines from the log being analyzed, for example:

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 a value 0173acc4from the second element in a list based on a string LOG_ADDR(i.e. in a key) (the reason is that the log will not always be consistent).

I am currently using the following one liner:

filter(lambda line: 'LOG_ADDR' in line, parsedLog)[0].split('\n')[-8:]
+4
source share
3 answers

You can use regex.

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

\S+ . , \S+(?=\n) , . Lookaheads - , char, , .

print stmt ,

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

>>> 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
>>> 

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


0173acc4
+5

:

[i.split()[i.split().index("LOG_ADDR")+1] for i in parsedLog if "LOG_ADDR" in i][0]
'0173acc4'

, , , split() :

for i in parsedLog:
    if "LOG_ADDR" in i:
        line_split = i.split()
        index_addr = line_split.index("LOG_ADDR") + 1
        print line_split[index_addr]

LOG_ADDR, , .

line_split.index("LOG_ADDR") + 1 , ,

+1
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']


print(re.search(r'\bLOG_ADDR\W+(\w+)', ''.join(parsedLog), re.MULTILINE).groups(1)[0])

0173acc4
+1
source

Source: https://habr.com/ru/post/1610274/


All Articles