【问题标题】:Find matching elements in nested list在嵌套列表中查找匹配元素
【发布时间】:2018-05-10 07:35:44
【问题描述】:

我有一个这样的嵌套列表:

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

最后一个元素是一种概率。 我需要的是找到元素,其中一个元素的第二个和第三个单词匹配另一个元素的第一个和第二个单词,例如:

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

并制作如下链:

one two 10 three 5 four 9 five

我知道第一步必须是元素的标记化:

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

所以我明白了

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

下一步应该是对列表的每个元素进行某种迭代搜索,但我对这种搜索的 Python 实现有点卡住了。 任何帮助,将不胜感激。

【问题讨论】:

  • 您需要得到什么结果?要遍历列表中的项目,请使用 for 循环:for item in list:
  • @Konstantin 感谢您的回复!正如我所写的,作为最终结果,我需要像“一二十三五四九五”这样的链,但即使你会帮助迭代搜索列表中的一对元素,它也会很好。

标签: python python-3.x list search


【解决方案1】:

这也有效:

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=' ')

第一个for i in matchloop 输出的位置:

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

第二个:

one two 10 three 5 four 9 five

【讨论】:

    【解决方案2】:

    我建议通过以下方式使用 pandas:

    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)
    

    我明白了:

        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
    

    【讨论】:

      【解决方案3】:

      你可以使用 itertools

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

      【讨论】:

        【解决方案4】:

        试试这个:

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

        输出:

        ['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']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-02-21
          • 1970-01-01
          • 1970-01-01
          • 2023-02-06
          • 2013-07-26
          • 2013-01-17
          • 2022-01-24
          • 1970-01-01
          相关资源
          最近更新 更多