3

I have a very long nested list. Here is a short example:

list = {{1.2, {1, 1, 1, 1}, {2, 2, 2}}, {0.9, {3, 3, 3, 3}, {4, 4, 4}}, {1.4, {4, 4, 4, 4}, {5, 5, 5}}}

Now I want to cancel all entries if the first entry of each part of the list (list[[i]]) is > 1. So that the new list would only consist of the second part of list (list[[2]])

newlist = {0.9, {3, 3, 3, 3}, {4, 4, 4}}

I have already tried my luck with Position and Delete, but with no success.

Thanks a lot for your help!

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Anna
  • 73
  • 1
  • 4

5 Answers5

3

A solution using Pick:

Pick[list, UnitStep[list[[All, 1]] - 1], 0]

(I subtract one from the first element and then grab all positions with a negative such element)

Pinguin Dirk
  • 6,519
  • 1
  • 26
  • 36
2

Rather than think of it as deleting certain unwanted parts of the list, you can equivalently think of it as selecting the parts you wish to keep. Accordingly, Select can be straightforwardly applied

Select[list, #[[1]] < 1 &]
{{0.9, {3, 3, 3, 3}, {4, 4, 4}}}

A. G. points out that this can be made more transparent by replacing the perhaps somewhat cryptic Part command [[1]] with

Select[list, First[#] < 1 &]

You can Flatten[%, 1] if you wish to get the levels exactly as described in the question.

bill s
  • 68,936
  • 4
  • 101
  • 191
1
list = {{1.2, {1, 1, 1, 1}, {2, 2, 2}},
        {0.9, {3, 3, 3, 3}, {4, 4, 4}},
        {1.4, {4, 4, 4, 4}, {5, 5, 5}}};

Using Replace:

Replace[list, {a_ /; a > 1, ___} :> Nothing, {1}]

({{0.9, {3, 3, 3, 3}, {4, 4, 4}}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
1
list = 
 {{1.2, {1, 1, 1, 1}, {2, 2, 2}}, 
  {0.9, {3, 3, 3, 3}, {4, 4, 4}}, 
  {1.4, {4, 4, 4, 4}, {5, 5, 5}}};

via Position

p = Position[list, {x_ /; x > 1, __}, 1]

{{1}, {3}}

Using Delete

Delete[p] @ list

{{0.9, {3, 3, 3, 3}, {4, 4, 4}}}

Using ReplaceAt (new in 13.1)

ReplaceAt[_ :> Nothing, p] @ list

{{0.9, {3, 3, 3, 3}, {4, 4, 4}}}

eldo
  • 67,911
  • 5
  • 60
  • 168
1

Using Sow/Reap:

list = {{1.2, {1, 1, 1, 1}, {2, 2, 2}}, {0.9, {3, 3, 3, 3}, {4, 4, 
    4}}, {1.4, {4, 4, 4, 4}, {5, 5, 5}}}

Scan[ If[First@# < 1, Sow@#, Nothing] & , list] // Reap // Last // First


{{0.9, {3, 3, 3, 3}, {4, 4, 4}}}

Syed
  • 52,495
  • 4
  • 30
  • 85