【问题标题】:Extract sub-list items based on matching strings from a larger list of lists基于匹配字符串从更大的列表列表中提取子列表项
【发布时间】:2021-01-13 03:09:39
【问题描述】:

我有以下搜索列表,可用于根据更大的列表列表搜索其中的任何项目。我希望结果是完整的子列表,但我似乎只得到项目本身。

search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']
new_lst=[]
for z in list_of_lists:
    yll = [x for x in z if any(w in x for w in search_list)]
    n_lst.append(yll)

new_lst 的输出:

new_lst = [['a xh'], ['3 b v'], []]

我是在获得此输出之后显示结果列表中与 search_list

中的任何项目匹配的所有项目
[['a xh', 'opp'], ['l n', '3b v'], []]

任何建议或提示将不胜感激。

谢谢

【问题讨论】:

    标签: python-3.x list list-comprehension


    【解决方案1】:

    如果search_list 的任何字符匹配,则appendnew_list 的子列表。

    search_list = ['a', 'b', 'x']
    list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']]
    
    new_list = []
    for sub in list_of_lists:
        for l in sub:
            if any(w in l for w in search_list):
                new_list.append(sub)
    print(new_list)
    
    # Output
    # [['axh', 'opp'], ['l n', '3b v']]
    

    【讨论】:

    • 正确。我正在考虑使用 set()... 来提高性能。
    • 感谢所有提供解决方案的人。我应该回到基础并按顺序完成循环。
    【解决方案2】:
    search_list = ['a', 'b', 'x']
    list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']]
    new_lst=[]
    for sublist in list_of_lists:
        for element in sublist:
            for item in search_list:
                if item in element and sublist not in new_lst:
                    new_lst.append(sublist)
    
    print(new_lst)
    

    输出:[['axh', 'opp'], ['l n', '3b v']]

    【讨论】:

      【解决方案3】:

      如果您不介意将子列表转换为元组,可以使用以下集合推导:

      result = {tuple(sublist) for sublist in list_of_lists for element in sublist for item in search_list
            if item in element}
      
      #output: {('axh', 'opp'), ('l n', '3b v')}
      

      【讨论】:

        猜你喜欢
        • 2021-07-02
        • 2023-03-28
        • 1970-01-01
        • 2022-10-19
        • 2013-04-24
        • 2013-06-18
        • 1970-01-01
        • 2018-12-17
        • 1970-01-01
        相关资源
        最近更新 更多