Reputation: 59
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
Upvotes: 2
Views: 1107
Reputation: 893
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)])
Upvotes: 0
Reputation: 78546
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']
Upvotes: 3