python - 当列表的元素在字符串中时,我想从字符串中删除列表中的元素
问题描述
认为
a = ['ab','bcd','efg','h']
b = ['wiab','wbcdz','rh','ksw','erer']
我想a
从 list中删除任何列出的字符b
。结果应该是 `['wi','wz','r','ksh','erer']
这是我尝试过的代码:
result = []
for i in b:
if not any(word in i for word in a):
result.append(word)
但是这段代码返回
result = ['ksw','erer']
请帮我
解决方案
def function(a,b):
result = []
for i in a:
for word in b:
if i in word:
result.append(word.replace(i,''))
return result
您的代码中的any
函数是不必要的。您需要遍历两个列表,然后检查您的子字符串是否在另一个列表的字符串中,在replace
包含子字符串的单词上调用该方法,然后将其添加到结果列表中
推荐阅读
- python - 错误:函数 'detectMultiScale' 中的 !empty()
- ios - SwiftUI .onAppear,只运行一次
- python - 如何使用 sympy 根据布尔方程组中的其他变量提取布尔变量的值?
- unity3d - 片段着色器 fmod,为什么不重复
- amazon-web-services - 为什么我会收到关于 nginx Web 服务器关闭或忙碌的错误?
- html - 无法在 React ERR_INVALID_URL 中显示从 mongodb 检索到的 base64 图像
- node.js - 当我执行“npm start”时,我在安装 reactjs 时遇到问题
- javascript - 使用Javascript将像素转换为视口单位的问题
- python - 使用提供的密钥加密文本 python
- react-native - React 无法识别 DOM 元素上的 `accessibilityState` 属性