how to keep elements of a list based on another list

前端 未结 3 1726
小鲜肉
小鲜肉 2020-12-03 16:38

I have two lists looking like:

list1 = [\'a\',\'a\',\'b\',\'b\',\'b\',\'c\',\'d\',\'e\',\'e\',\'g\',\'g\']

list2 = [\'a\',\'c\',\'z\',\'y\']
3条回答
  •  误落风尘
    2020-12-03 17:15

    One alternative approach with numpy:

    import numpy as np
    
    np.asarray(list1)[np.in1d(list1, list2)].tolist()
    #['a', 'a', 'c']
    

提交回复
热议问题