Let's say I have a list:
list=Table[{RandomReal[],RandomReal[],RandomReal[]}, {i,1,100}];
I'd like to make a new list based on conditions. Now I've seen that I should use the Select function, but I don't understand how to define the condition where selection should be based on some element of nested list.
Someone asked a similar question and the answer I like was:
data = {{0,2},{2,3},{4,3},{5,4},{8,4}};
filtered = Select[data, First[#]>3&];
However this only works if the condition is set on first element of sublist. In my case:
Select[list,0.2>First[#]>0.1&]
gives all members of the list where 1. element of sublist is between 0.1 and 0.2. But what if I wanted to make selection based on a second element of a sublist, or in general for the nth element?
Also an example with combination of elements would be nice, for example where the sum of first 2 elements of sublist is smaller than 0.5.
First, generating the list is easier as:
list = RandomReal[1, {100, 3}];
You can use Part (see the docs!!), which is equivalent to the [[ ]] syntax, to take the nth element. E.g. this selects those items which have a second element larger than 0.1.
Select[list, #[[2]] > 0.1 &]
Alternatively use
Cases[list, l_ /; l[[2]] > 0.1]
or
Cases[list, {_, y_, _} /; y > 0.1]
I recommend you explore the tutorials in the documentation, especially the part about list manipulation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With