Home > Software design >  How to compare the value of two lists is the same and match the Elements?
How to compare the value of two lists is the same and match the Elements?

Time:08-28

I have two list of list values

first value is

first = [['Admin', 'access','30'],['Admin', 'access','32'],['sam', 'ok','10'],['client', 'access', '50']]

second value is

second = [['test.com.Admin', 'access','30'],['john', 'ok', '70'],['robert\\client', 'access', '40']]

how to compare the value of the first list entry [0] is the same as the second list [0] but the value of the second list is some string and symbol is there

so how to match the value of my first list with my second list if it matches then print the result like this

if the value is like this ['Admin', 'access','30'],['Admin', 'access','32'] its get only one value because some element is different. 31.32 does not match,

example: so if [0] matches, the entire first value is retrieved, even the other item doesn't match

output result:

['Admin', 'access','30']
['Admin', 'access','32']
['client', 'access', '50']
['sam', 'ok','10']

so i need to omit some substrings and symbols

if my first list[0] matches this second list[0] for any name

Is it possible to use regular expression matching?

code: (but it does not get correctly)

import re
first = [['Admin', 'access','30'],['Admin', 'access','32'],['sam', 'ok','10'],['client', 'access', '50']]
second = [['test.com.Admin', 'access','30'],['john', 'ok', '70'],['robert\\client', 'access', '40']]
for one in first:
    for two in second:
        print({i:j  for j in one for i in two if re.match(i,j)})

CodePudding user response:

Seems like you could use zip and endswith since the matches are always at the same position and the matching portion of the username is always at the end of the string in the second list:

>>> first = [['Admin', 'access'],['sam', 'ok'],['client', 'access'],['sam', 'failed']]
>>> second = [['test.com.Admin', 'access'],['john', 'ok'],['robert\\client', 'access'],['cab.com//sam', 'failed']]
>>> for f, s in zip(first, second):
...     if s[0].endswith(f[0]):
...         print(f)
...
['Admin', 'access']
['client', 'access']
['sam', 'failed']

CodePudding user response:

Convert to symbols then compare

First define a symbol, convert both lists to symbols, then compare the lists

SYMBOL DEFINITION

I'm going to use the definition of a python identifier (limited to ASCII) at the end of a string.

symbol_rexp = re.compile("[a-zA-Z_][a-zA-Z_0-9]*$")

MATCH

Use symbol_rexp to match symbols in both lists and replace with the match.

  • Related