【问题标题】:Remove elements from a list who's specific substrings repeat in other elements从列表中删除特定子字符串在其他元素中重复的元素
【发布时间】:2018-09-08 07:07:15
【问题描述】:

如何查找列表元素的一个或多个特定子字符串是否重复。与列表的其他元素一样,然后通过仅保留包含这些子字符串的第一个元素并删除所有其他元素(包含重复项的元素)来使列表唯一。

例子:

SUBSTRINGS=['banana','chocolate']
MYLIST=['1 banana cake','2 banana cake','3 cherry cake','4 chocolate cake','5 chocolate cake','6 banana cake','7 pineapple cake']

在这种情况下,重复的子字符串是bananachocolate。处理后的列表应该变成:

MYLIST=['1 banana cake','3 cherry cake','4 chocolate cake','7 pineapple cake']

【问题讨论】:

标签: python string python-3.x list substring


【解决方案1】:

在这里,我们通过迭代原始MYLIST 来构造一个列表new_list。我们使用all_substrings 集来跟踪哪些子字符串(来自SUBSTRINGS)已被使用。

SUBSTRINGS = {'banana', 'chocolate'}
MYLIST = ['1 banana cake', '2 banana cake', '3 cherry cake', '4 chocolate cake', '5 chocolate cake', '6 banana cake', '7 pineapple cake']

new_list = []
all_substrings = set()
for el in MYLIST:
    # All substrings of this element
    substrings = set(el.split())
    # Add this element if it does not have any substrings in common
    # with the all_substrings set.
    if not any(substring in all_substrings for substring in substrings):
        new_list.append(el)
    # Add current substrings which are also present
    # in SUBSTRINGS to all_substrings.
    all_substrings |= (substrings & SUBSTRINGS)
print(new_list)

【讨论】:

    【解决方案2】:

    这是一个比jmd_dk 发布的更简单的答案。据我所知,两者都工作正常。

    SUBSTRINGS = {'banana', 'chocolate'}
    MYLIST = ['1 banana cake', '2 banana cake', '3 cherry cake', '4 chocolate cake', '5 chocolate cake', '6 banana cake', '7 pineapple cake']
    m = []
    
    for substr in MYLIST:
        if any(el in substr for el in SUBSTRINGS):
            if not any(substr.split()[1] in n for n in m):
                m.append(substr)
        else:
            m.append(substr)
    
    print(m)
    

    【讨论】:

    • 依赖子字符串(这里是 'banana''chocolate')总是第 2 个单词(索引 1)不是一个好主意。
    猜你喜欢
    • 2011-03-25
    • 2015-05-16
    • 2020-04-05
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2012-10-08
    • 2021-08-15
    相关资源
    最近更新 更多