Message Boards Message Boards

0
|
12287 Views
|
4 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Compare the elements of 2 Lists for similar elements?

Posted 8 years ago

Hi All, how to - Compare the elements of 2 Lists for similar elements?

Given the two lists below.

list1 = {1,3,4,7,10,12,15,17,19,24,26,29,32,35};
list2 ={2,5,6,7,8,9,11,12,14,19,25,27,29,30};

I trying to setup the coding that compares or matches each element in list1 with each element in list2 & then providing an output of similar elements in each of the lists.

(i) The idea answer would be Answer = {7,12,19,29}

(ii) Additionally it would great if I had the positions of all of these elements {7,12,19,29} in list1 & list2.

Many thanks for your help & attention. Best regards, Lea.

POSTED BY: Lea Rebanks
4 Replies

Dear @Lea Rebanks, you have been getting help on this forum for a long time already, but you still do not post properly your code and moderators forced to edit your posts every time. Please read how to post properly:

http://community.wolfram.com/groups/-/m/t/270507

POSTED BY: Moderation Team

One way to do this:

In[1]:= list1={1,3,4,7,10,12,15,17,19,24,26,29,32,35};list2={2,5,6,7,8,9,11,12,14,19,25,27,29,30};
In[2]:= pos=Position[Table[MemberQ[list1,list2[[i]]],{i,1,Length[list2]}],True]//Flatten
Out[2]= {4,8,10,13}
In[3]:= list2[[pos]]
Out[3]= {7,12,19,29}
POSTED BY: Tim Mayes
Posted 8 years ago

The first part is quite easy

list1 = {1, 3, 4, 7, 10, 12, 15, 17, 19, 24, 26, 29, 32, 
  35}; list2 = {2, 5, 6, 7, 8, 9, 11, 12, 14, 19, 25, 27, 29, 
  30}; position = Intersection[list1, list2]

There are probably more elegant ways to do the second part, but this works

Flatten[Table[
  Position[list1, position[[q]]], {q, 1, Length[position]}]]

and

Flatten[Table[
  Position[list2, position[[q]]], {q, 1, Length[position]}]]

Paul.

POSTED BY: Paul Cleary
Posted 8 years ago

Perfect! Many thanks Paul. Really appreciated.

POSTED BY: Lea Rebanks
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract