如何删除以python 3中的特定元素开头的子列表?
updated_code_result_2_2 =[["DR JOHN","HOSPITAL"],["TOTAL CHARGES","5OO"],["yes"]]
def remove_dr(updated_code_result_2_2):
rem_list = []
rem_ele_list = ['DR','TOTAL']
for x in updated_code_result_2_2:
for i in rem_ele_list:
if not x[0].startswith(i):
rem_list.append(x)
print(rem_list)
return rem_list
remove_dr(updated_code_result_2_2)
预期输出: [[“是”]]
答案 0 :(得分:2)
您非常接近。您可以在str.startswith
EX:
updated_code_result_2_2 =[["DR JOHN","HOSPITAL"],["TOTAL CHARGES","5OO"],["yes"]]
def remove_dr(updated_code_result_2_2):
rem_list = []
rem_ele_list = ('DR','TOTAL')
for x in updated_code_result_2_2: #Iterate each element
if not x[0].startswith(rem_ele_list): #Check if element startswith anything from rem_ele_list
rem_list.append(x)
return rem_list
print(remove_dr(updated_code_result_2_2))
答案 1 :(得分:2)
我只是更改您现有的代码,使用temp
变量,如果条件,则使用if条件检查起始元素在哪里匹配。
在内部for-loop
中添加中断条件,并设置temp变量为true。
updated_code_result_2_2 =[["DR JOHN","HOSPITAL"],["TOTAL CHARGES","5OO"],["yes"]]
def remove_dr(updated_code_result_2_2):
rem_list = []
rem_ele_list = ['DR','TOTAL']
for x in updated_code_result_2_2:
temp = False
for i in rem_ele_list:
if x[0].startswith(i):
temp = True
break
if temp is False:
rem_list.append(x)
print(rem_list)
return rem_list
remove_dr(updated_code_result_2_2)
O / P:
[['yes']]
答案 2 :(得分:0)
我将对现有解决方案进行一些优化。首先,我要指出@bharatk的答案可以通过使用Python for
循环的else
子句来清理:
updated_code_result_2_2 =[["DR JOHN","HOSPITAL"],["TOTAL CHARGES","5OO"],["yes"]]
def remove_dr(updated_code_result_2_2):
rem_list = []
rem_ele_list = ['DR','TOTAL']
for x in updated_code_result_2_2:
for i in rem_ele_list:
if x[0].startswith(i):
break
else:
rem_list.append(x)
print(rem_list)
return rem_list
remove_dr(updated_code_result_2_2)
第二,我要指出@Rakesh的解决方案可以使用列表推导在一行中完成:
updated_code_result_2_2 =[["DR JOHN","HOSPITAL"],["TOTAL CHARGES","5OO"],["yes"]]
def remove_dr(updated_code_result_2_2):
rem_list = [x for x in updated_code_result_2_2 if not x[0].startswith(('DR', 'TOTAL'))]
print(rem_list)
return rem_list
remove_dr(updated_code_result_2_2)
这两种情况都会导致:
[['yes']]