1

I have two lists :

v = ['bus','car','person','bus']
vehicles=['car','bus','truck','motorcycle','auto-rickshaw']

I need a list M which should compare list v with vehicles and results like

M = ['car', 'bus', 'bus']

Please help and suggest. I have referred Common elements comparison between 2 lists but it doesn't answers my question.

be_real
  • 180
  • 1
  • 1
  • 12
  • The intersection of two lists is exactly what you want. What results does the answer in the linked post return you, which is wrong? – OneCricketeer Jan 01 '22 at 13:52
  • Is the order important? – mozway Jan 01 '22 at 13:53
  • 1
    @OneCricketeer Desired output is `[car, bus, bus]` linked question uses sets to solve which removes duplicate values. – Ch3steR Jan 01 '22 at 13:53
  • @Ch3 Not all the answers use sets https://stackoverflow.com/a/55385567/2308683 – OneCricketeer Jan 01 '22 at 13:54
  • 1
    `O(n^2)` solution though @OneCricketeer OP did not comment about efficiency in this question but this question can be answered in `O(n)` like mozway did. Much better IMO than the linked answer and I believe it would useful to future readers(Assuming a duplicate doesn't exist). – Ch3steR Jan 01 '22 at 13:59

1 Answers1

3

If order doesn't matter (or rather, if you want to keep the order in v), use a list comprehension with a set as reference for efficient identification of members (O(1) per item in v, so O(n) in total):

v = ['bus','car','person','bus']
vehicles=['car','bus','truck','motorcycle','auto-rickshaw']

ref = set(vehicles)

M = [e for e in v if e in ref]

output: ['bus', 'car', 'bus']

If really you want to have the order of vehicles, sorting afterwards is probably the most efficient:

order = {k:v for v,k in enumerate(vehicles)}
M2 = sorted(M, key=order.get)

output:

['car', 'bus', 'bus']
mozway
  • 194,879
  • 13
  • 39
  • 75