TransWikia.com

Functional realisation of do-loop

Mathematica Asked on June 4, 2021

I’m currently optimising my code and I’m using a lot of loops, so I was wondering if there is a smarter or faster way to do things like:

Do[If[MemberQ[List1[[II]], List2_], AppendTo[Newlist1, List1[[II]]]], {II, Length[List1]}]

I guess using Apply would be better, but since I’m not primary a programmer I would be happy for any help. Thank you!

2 Answers

First question: select those elements in list1 that also appear in list2:

list1 = {a, b, c, d, e, f};
list2 = {e, g, i};
Select[list1, MemberQ[list2, #] &]
(*    {e}    *)

Second question: select those elements in list1 that have a factor that is in list2:

list1 = {a b c d, x y z, m n o};
list2 = {a, r, l, m};
Select[list1, IntersectingQ[List @@ #, list2] &]
(*    {a b c d, m n o}    *)

Correct answer by Roman on June 4, 2021

Try the following, first remove from the first list the elements of the second one:

lst1 = {a, b, c, d, e, f, g};
lst2 = {b, c, g};
Complement[lst1, lst2]
(*  {a, d, e, f}  *)

and then append it to the newList.

Clear[newList];
newList = {AA, BB, CC}; (*This is the initial newList*)
AppendTo[newList, Complement[lst1, lst2]] // Flatten
(*  {AA, BB, CC, a, d, e, f}   *)

Have fun!

Answered by Alexei Boulbitch on June 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP