How to remove a sublist which starts with particular element in 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)
Expected Output: [["yes"]]
You are pretty close. You can use a tuple inside 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))
I just change your existing code, use temp
variable and if condition, if condition to check where the start element is matched. Add break condition inside inner for-loop
and set and temp variable is 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']]
I'll offer a few optimizations to the existing solutions. First, I'll point out that @bharatk's answer can be cleaned up by making use of the Python for
loop's else
clause:
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)
Second, I'll point out that @Rakesh's solution can be done in a single line using a list comprehension:
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)
Both of these also result in:
[['yes']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.