2
$\begingroup$

I need to change some elements at the second level of a list based on some conditions.

I have the following list of objects of the same type:

myList = {{1000, 12, 1000, 0, "Open", "Good", 0}, {2000, 24, 2000, 0, "Open", "Good", 0}, {2000, 12, 2000, 0, "Open", "Good", 0}, {10000, 12, 10000, 0, "Open", "Good", 0}, {2000, 24, 2000, 0, "Open", "Good", 0}, {2000, 24, 2000, 0, "Open", "Good", 0}, {10000, 36, 10000, 0, "Open", "Good", 0}, {10000, 36, 10000, 0, "Open", "Good", 0}, {10000, 36, 10000, 0, "Open", "Good", 0}, {1000, 24, 1000, 0, "Open", "Good", 0}}

Each element represents the info about concrete object. I need to modify list in the following way:

  • modify only elements where Part 5 of element is "Open" and Part 7 of element is 0
  • modify only Part 6 of element, change it to "Bad" if RandomVariate[NormalDistribution[]] > 0.2

I know how to achieve the goal using For[ but may be there is a possibility to do it in functional way.

$\endgroup$
5
  • 1
    $\begingroup$ Look up Map[] and If[]. $\endgroup$
    – J. M.'s torpor
    Oct 9 '15 at 18:10
  • $\begingroup$ I spent 3 hours reading about Map[], If[] and other such stuff but cat solve the concrete question. I'll appriciate a working piece of code. $\endgroup$ Oct 9 '15 at 18:15
  • $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$
    – bbgodfrey
    Oct 9 '15 at 18:23
  • 3
    $\begingroup$ (# /. {a1_, a2_, a3_, a4_, a5 : "Open", a6_, a7 : 0} :> {a1, a2, a3, a4, a5, "Bad", a7} /; RandomVariate[NormalDistribution[]] > 0.2) & /@ myList $\endgroup$ Oct 9 '15 at 18:28
  • $\begingroup$ So you mean we need all three conditions at once:myList[[5]]=="Open", myList[[7]]==0 and RandomVariate[NormalDistribution[]] > 0.2? I am confused (my normal state). Everyone of your rows has "Open" and 0 for elements 5 and 7. $\endgroup$ Oct 10 '15 at 4:07
1
$\begingroup$

Here is one way:

ReplacePart[myList, {i_, 6}  :> "Bad" /;
  myList[[i, {5, 7}]] == {"Open", 0} && RandomVariate[NormalDistribution[]] > 0.2 ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.