为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除包含在同一字符串列表中的其他字符串中的字符串?

如何删除包含在同一字符串列表中的其他字符串中的字符串?

www说 2022-01-05 13:07:23
我有一个字符串列表,需要删除其他项目中包含的项目,如下所示:a = ["one", "one single", "one single trick", "trick", "trick must", "trick must get", "one single trick must", "must get", "must get the job done"]我只需要删除同一列表中另一个字符串中包含的每个字符串,例如:“one”包含在“one single”中,因此必须删除,然后“one single”包含在“one single trick”中,因此还需要被丢弃我努力了:b=afor item in a:    for element in b:        if item in element:            b.remove(element)预期结果:a = ["trick must get", "one single trick must", "must get the job done"]任何帮助将不胜感激!提前致谢!
查看完整描述

3 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

列表推导式结合 Python 的any函数应该可以很好地做到这一点:


a = [phrase for phrase in a if not any([phrase2 != phrase and phrase in phrase2 for phrase2 in a])]

结果:


>>> a = ["one", "one single", "one single trick", "trick", "trick must", "trick must get", "one single trick must", "must get", "must get the job done"]

>>> a = [phrase for phrase in a if not any([phrase2 != phrase and phrase in phrase2 for phrase2 in a])]

>>> a

['trick must get', 'one single trick must', 'must get the job done']


查看完整回答
反对 回复 2022-01-05
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

解决O(n)时间复杂度问题的一种有效方法是使用一个集合来跟踪给定短语的所有子短语,从最长的字符串迭代到最短的字符串,并且仅在以下情况下才将字符串添加到输出中它不在子短语集中:


seen = set()

output = []

for s in sorted(a, key=len, reverse=True):

    words = tuple(s.split())

    if words not in seen:

        output.append(s)

    seen.update({words[i: i + n] for i in range(len(words)) for n in range(len(words) - i + 1)})

output 变成:


['one single trick must', 'must get the job done', 'trick must get']


查看完整回答
反对 回复 2022-01-05
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

不是一个有效的解决方案,但通过从最长到最小排序并删除最后一个元素,我们可以检查每个元素是否在任何地方都作为子字符串出现。


a = ['one', 'one single', 'one single trick', 'trick', 'trick must', 'trick must get', 

     'one single trick must', 'must get', 'must get the job done']

a = sorted(a, key=len, reverse=True)

b = []

for i in range(len(a)):

    x = a.pop()

    if x not in "\t".join(a):

        b.append(x)


# ['trick must get', 'must get the job done', 'one single trick must']


查看完整回答
反对 回复 2022-01-05
  • 3 回答
  • 0 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号