简体   繁体   中英

Find matching elements in nested list

I have a nested list like this:

lst = [['one two', 'three', '10'], ['spam eggs', 'spam', '8'],
       ['two three', 'four', '5'], ['foo bar', 'foo', '7'],
       ['three four', 'five', '9']] 

The last element is a kind of probability. What I need is to find elements, where second and third words of one element match first and second word of another, for example:

['one two', 'three', '10'] match ['two three', 'four', '5'] match  ['three four', 'five', '9']

And make chains like:

one two 10 three 5 four 9 five

I understand that first step must be tokinization of elements:

lst = ([' '.join(x).split() for x in lst])
for i in lst: 
    print(i)

So I get

['one', 'two', 'three', '10']
['spam', 'eggs', 'spam', '8']
['two', 'three', 'four', '4']
['foo', 'bar', 'foo', '7']
['three', 'four', 'five', '9']

Next step should be some kind of iterative search over each element of the list, but I am a bit stuck with Python realization of such search. Any help would be appreciated.

I would suggest using pandas in the following way:

import pandas as pd

lst = [['one two', 'three', '10'], ['spam eggs', 'spam', '8'],
   ['two three', 'four', '5'], ['foo bar', 'foo', '7'],
   ['three four', 'five', '9']]

lst = [' '.join(x).split() for x in lst]

#Create a dataframe and merge using the adequate columns

df = pd.DataFrame(lst)
matchedDF = df.merge(df,how='inner',left_on=[1,2],right_on=[0,1],suffixes=['left','right'])

# remove unneccessary columns
cols=matchedDF.columns.tolist()

matchedDF = matchedDF[cols[2:]]

print(matchedDF)

I get:

    0left  1left  2left 3left 0right 1right 2right 3right
0   one    two  three    10    two  three   four      5
1   two  three   four     5  three   four   five      9

This works also:

lst = [['one two', 'three', '10'],['spam eggs', 'spam', '8'], ['two three', 'four', '5'], ['foo bar', 'foo', '7'], ['three four', 'five', '9']] 
lst = ([' '.join(x).split() for x in lst])

match, first = [], True
for i in lst:
    for j in lst:
        if i[0] == j[1] and i[1] == j[2]:
            if first:
                match.append(j)
                first = False
            match.append(i)

for i in match:
    if i == match[len(match)-1]: print(i)
    else: print ("{} match ".format(i), end=' ')

for i in match:
    if i == match[0]: print (i[0], i[1], i[3], end=' ')
    elif i == match[len(match)-1]: print (i[1], i[3], i[2])
    else: print (i[1], i[3], end=' ')

Where the first for i in match loop outputs:

['one', 'two', 'three', '10'] match  ['two', 'three', 'four', '5'] match ['three', 'four', 'five', '9']

And the second:

one two 10 three 5 four 9 five

You can use itertools

# import itertools
import itertools
# search for the item after generating a chain
item in itertools.chain.from_iterable(lst)

Try this one:

lst = [['one two', 'three', '10'], ['spam eggs', 'spam', '8'],
       ['two three', 'four', '5'], ['foo bar', 'foo', '7'],
       ['three four', 'five', '9']]

lst = [' '.join(x).split() for x in lst]
for i in lst: 
    print(i)

# ---------------------------------------------------------------

st = set()
for i in [set(x) for x in lst]:
    st |= i

print(st)
print(list(st))

Output:

['one', 'two', 'three', '10']
['spam', 'eggs', 'spam', '8']
['two', 'three', 'four', '5']
['foo', 'bar', 'foo', '7']
['three', 'four', 'five', '9']
{'bar', 'spam', '9', 'one', 'five', 'three', 'two', '8', 'four', '5', 'foo', '10', '7', 'eggs'}
['bar', 'spam', '9', 'one', 'five', 'three', 'two', '8', 'four', '5', 'foo', '10', '7', 'eggs']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM