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

2
  • 1
    This is called getting the intersection of the lists btw. Python probably has a built-in function for this already. Commented Jul 4, 2017 at 11:24
  • Possible duplicate of Stopword removal with NLTK Commented Jul 4, 2017 at 11:27

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.
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)])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.