python - 如何检查列表中的元素(b)是否包含同一列表中的元素(a)。比删除元素 (a)
问题描述
如果它在另一个元素中,我需要删除它
def c_counter_check(new_filters): #new filters is an list
for i in new_filters_splited[:]:
index = new_filters_splited.index(i) #get index of an i
mylist = new_filters_splited[:index] + new_filters_splited[index + 1:] # create a compare list without i
for a in mylist[:]:
if a.__contains__(i): #check if an element from mylist contains an i
new_filters_splited.remove(i) #if yes than remove i from new_filters_splited
return new_filters_splited
例如,如果我的列表是['a', 'ab', 'ac', 'ab', 'abac']
我需要删除'a' and 'ab' and 'abac' and 'ac'
的,结果应该只是['a']
解决方案
def deduplicate(list_to_deduplicate):
elems = set()
rest = []
for el in list_to_deduplicate:
if el not in elems:
elems.add(el)
rest.append(el)
return rest
def c_counter_check(list_to_filter):
res = []
lst_s = deduplicate(list_to_filter)
for index, attribute in enumerate(lst_s):
mylist = lst_s[:index] + lst_s[index + 1:]
global checker
checker = 0
if any(attribute in b for b in mylist):
res.append(attribute)
for b in mylist:
if attribute.__contains__(b):
res.remove(attribute)
break
else:
if not any(attribute in r for r in res):
res.append(attribute)
if any(b in attribute for b in mylist):
res.remove(attribute)
return res
这是完整的工作解决方案感谢来自 discord 的 @ConfusedReptile 创建deduplicate
函数
推荐阅读
- php - oci_bind_by_name 和值类型问题或如何调试
- python - 有没有办法制作也计算出现次数的虚拟变量?
- authentication - 在现有 IE 窗口中从命令行打开链接
- python-3.x - python3中的语法错误'isdigit'问题
- python - 为什么我收到以下错误消息:+ 的不支持的操作数类型:'int' 和 'str'。请参阅下面的 python 规则正文
- c# - 在 API 请求过程中使用并行 foreach?
- java - 使用 Java 制作 GUI 时从哪里开始(Swing 是否已弃用?)
- reactjs - 要使用 SmartCard 身份验证制作 React 应用程序,我应该使用 pkcs11 吗?
- jquery - 如何知道拖动了哪个类draggable
- excel - 函数问题:Excel VBA 中的日期过滤器