我有一个子字符串列表,我将从另一个列表中删除, 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 点击链接欢迎加入社区大社群。
使用python set可以使程序更简洁
mylist = ['abc123', 'def456', 'ghi789','ghi123',"123"]
sub = ['123','456']
print(list(set(mylist)-set(sub)))
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]
你需要
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']
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。