【问题标题】:Compare two list of list in python比较python中的两个列表列表
【发布时间】:2018-03-19 04:41:47
【问题描述】:

我有两个列表

lst1=[['hey','jude' ,'fox'],['how','you','do']]
lst2=[['hey','paul'],['how','do']]

我想将 lst1 中的每个列表与 lst2 中的每个列表进行比较。如果他们有大于或等于 1 的常用词。那么我需要将更大的列表附加到一个新的列表中。如果他们有共同的词 例如:['hey', 'jude','fox']['hey','paul'] 进行比较,因为它们有共同的单词 hey,重复一次。我需要将更大的列表 ['hey', 'jude','fox'] 附加到一个新列表中。

【问题讨论】:

标签: python python-2.7 python-3.x list append


【解决方案1】:

这是您的解决方案:

lst1=[['hey','jude' ,'fox'],['how','you','do']]
lst2=[['hey','paul'],['how','do']]
    new_list=[]
    
    for item in lst1:
        for item_1 in lst2:
            if isinstance(item_1,list):
                for sub_item in item_1:
                    if sub_item in item:
                        if len(sub_item)>=1:
                            if len(item)>len(item_1):
                                if item not in new_list:
                                    new_list.append(item)
                            elif len(item_1)>len(item):
                                if item_1 not in new_list:
                                    new_list.append(item_1)
    
    
                        if len(sub_item)<2:
                            if sub_item not in new_list:
                                new_list.append(sub_item)
                                new_list.append(item)
    
    
    
    print([j for i,j in enumerate(new_list) if j not in new_list[:i]])

P.S:你的问题很混乱,你的意思是什么 “大于或等于 1 的单词。”你的意思是单词的长度还是单词的匹配?我假设了单词的长度。

测试:

与您的清单:

输出:

[['hey', 'jude', 'fox'], ['how', 'you', 'do']]

当列表一的 comman 字母少于 2 len 时:

lst1=[['hey','jude' ,'fox'],['how','you','do'],["wow"],["wllla","wlahi","aasma"],["h","i","j"]]
lst2=[['hey','paul'],['how','do'],["wllla"],["h"]]

输出:

[['hey', 'jude', 'fox'], ['how', 'you', 'do'], ['wllla', 'wlahi', 'aasma'], ['h', 'i', 'j'], 'h']

当第二个列表有最大的共同列表词时:

lst1=[['hey','jude' ,'fox'],['how','you','do'],["wow"],["wllla","wlahi","aasma"],["h","i","j"],["abc","def"]]
lst2=[['hey','paul'],['how','do'],["wllla"],["h"],["abc","def","ghi"]]

输出:

[['hey', 'jude', 'fox'], ['how', 'you', 'do'], ['wllla', 'wlahi', 'aasma'], ['h', 'i', 'j'], 'h', ['abc', 'def', 'ghi']]

如果你想避免嵌套,将逻辑分解成一个函数 减少嵌套。

【讨论】:

    猜你喜欢
    • 2023-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多