开发者社区> 问答> 正文

如何在Python中查找或删除列表中的子串列表

我有一个子字符串列表,我将从另一个列表中删除, mylist

mylist = ['abc123', 'def456', 'ghi789','ghi123']

sub = ['123','456']
print ([s for s in mylist if sub[j] in s for j in sub])
这给出了错误。有没有其他方法可以找到这个。

预期产量:

['abc123','ghi123','def456']
本问题及下方已被采纳的回答均来自云栖社区【Python技术进阶大群】。https://yq.aliyun.com/articles/690084 点击链接欢迎加入社区大社群。

展开
收起
一码平川MACHEL 2019-02-28 14:44:03 4879 0
3 条回答
写回答
取消 提交回答
  • 使用python set可以使程序更简洁
    mylist = ['abc123', 'def456', 'ghi789','ghi123',"123"]

    sub = ['123','456']

    print(list(set(mylist)-set(sub)))

    2019-07-17 23:29:48
    赞同 展开评论 打赏
  • mylist = ['abc123', 'def456', 'ghi789','ghi123']
    sub = ['123','456']
    new_list = []

    先确定正常的写法

    for my_str in mylist:

    for sub_str in sub:
        if sub_str in my_str:
            new_list.append(my_str)

    print new_list

    然后在理解这颗语法糖

    print [j for i in range(5) for j in range(i)]

    最后改写下

    print [my_str for my_str in mylist for sub_str in sub if sub_str in my_str]

    2019-07-17 23:29:48
    赞同 展开评论 打赏
  • 你需要

    mylist = ['abc123', 'def456', 'ghi789','ghi123']
    sub = ['123','456']

    print ([i for i in mylist for j in sub if j in i])
    输出:

    ['abc123', 'def456', 'ghi123']

    2019-07-17 23:29:47
    赞同 1 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载