2

I would like to compare two string lists, locate the common strings and store the common strings in a new list.

For example:

my_list1=['      4,         -40.,         -12.\n',
 '      5,         -40.,         -15.\n',
 '      6,         -40.,         -18.\n',
 '      7,         -40.,         -21.\n',
 '      8,         -40.,         -24.\n',
 '      9,         -40.,         -27.\n',
 '     14,         -30.,         -30.\n',
 '     15,         -28.,         -30.\n']

my_list2=['49',
 '50',
 '51',
 '10',
 '53',
 '54',
 '55',
 '56',
 '57',
 '58',
 '59',
 '60',
 '6162',
 '15',
 '64',
 '65',
 '66']

What I want to do is compare each of the strings of my_list2 with the beginning of the strings in my_list1.

For example my_list1 contains '15' from my_list2 in [ '15, -28., -30.\n'] so i want a new list which is going to save all the common strings

Dadep
  • 2,796
  • 5
  • 27
  • 40
Giomix88
  • 57
  • 6

2 Answers2

3

You can use str.startswith which can take a tuple of items as argument. Left strip each item in the first list and check if the item startswith any of the strings in the second list:

t = tuple(my_list2)
lst = [x for x in my_list1 if x.lstrip().startswith(t)]
print lst
# ['     15,         -28.,         -30.\n']
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • nice use of the `startswith()` there. +1. Would it be slower with `any()`? Like `lst = [x for x in my_list1 if any(x.lstrip().startswith(y) for y in my_list2)]`. It should be the same thing, right? – Ma0 Jul 04 '17 at 11:31
  • @Ev.Kounis No it won't. A single call (albeit with a tuple of params) will be much faster than a `*n` call in a **gen. exp.** wrapped by `any`. – Moses Koledoye Jul 04 '17 at 11:35
0
my_list1_new = [i.strip().split(",")[0] for i in my_list1 ]
for i in my_list2:
    if i in my_list1_new:
        print(my_list1[my_list1_new.index(i)])
Manish Goel
  • 843
  • 1
  • 8
  • 21