0
$\begingroup$

Let a be a list of lists like this:

a= {{"apples", "pears", 1, 17},
    {"pineapples", "apples", 5, 7},
    {"yes", "building", 4, 7}}

How can I make a list b containing only elements of a for which the nth element meets an arbitrary criterion?

Let us say for example that n is 3 and the criterion is "must be greater than 2". Then b would be

{{"pineapples", "apples", 5, 7},
    {"yes", "building", 4, 7}}.
$\endgroup$

1 Answer 1

2
$\begingroup$

No sooner do I post the question than I think I've found the answer!

 b = Select[a, #[[3]] > 2 &]
$\endgroup$
3
  • 2
    $\begingroup$ Also Cases[a, {_, _, n_, ___} /; n > 2] $\endgroup$
    – MelaGo
    Commented Oct 19, 2023 at 5:25
  • $\begingroup$ @MelaGo - Thanks for this. Your version is more widely useful because Cases can match strings and numbers, whereas Select matches numbers only. $\endgroup$
    – tell
    Commented Oct 23, 2023 at 17:34
  • $\begingroup$ You're welcome. You can use Select with any expression that evaluates to True, for example Select[a, #[[2]] == "apples" &] or Select[a, StringMatchQ[#[[2]], "apples"] &] $\endgroup$
    – MelaGo
    Commented Oct 23, 2023 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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