Home > Software design >  Python3 list remove string is too much time,i need efficient way
Python3 list remove string is too much time,i need efficient way

Time:07-07

This is my data list

data_list = [
'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2372307693.jpg', 'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2616355133.jpg',
 'http://42.194.197.95:8001/poison_img_url', 
'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg', 'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2578474613.jpg', 'https://img9.doubanio.com/view/photo/s_ratio_poster/public/p457760035.jpg', 'https://img1.doubanio.com/view/photo/s_ratio_poster/public/p524964039.jpg', 'https://img3.doubanio.com/view/photo/s_ratio_poster/public/p511118051.jpg', 'https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2557573348.jpg', 'https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2561716440.jpg',
 'http://42.194.197.95:8001/poison_img_url', 
'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p492406163.jpg',
 'http://42.194.197.95:8001/poison_img_url'
]

I want to remove string in the list,but,My solution is too time consuming,i need some efficient way

def make_url(data_list,remove_str):
  img_array = []
  #print(result)
  for index,x in enumerate(data_list):
     if(remove_str == x):
         data_list.append(x)
  print(url_list)

if __name__ == "__main__":

    remove_str = 'http://42.194.197.95:8001/poison_img_url'
    t1 = time.time()
    make_url(data_list,remove_str)
    t2 =time.time()
    print(t2-t1)//7s too slowly

CodePudding user response:

use list comprehension to keep items not equal to x

def make_url(data_list, remove_str):

    data_list[:] = [x for x in data_list if remove_str != x]  # this will change the original list
    

if you want to return a new list then use return statement inside your function.

return [x for x in data_list if remove_str != x]

CodePudding user response:

You could use the filter method:

value_to_be_removed = 'http://42.194.197.95:8001/poison_img_url'
result = list(filter(lambda val: val != value_to_be_removed, url_list))
  • Related