Message Boards Message Boards

0
|
4616 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Selecting elements from a list based on criteria

Posted 9 years ago

Hi there,

I'm looking to extract elements from a list that meet a certain criterion: namely, that the sum of the first and second elements is greater than or equal to 70. Here's what I've tried:

points = Table[{racing, sport, 8*racing + 12*sport}, {racing, 0, 40}, {sport, 0, 60}]
selected = Select[points, points[[All, All, 1]] + points[[All, All, 2]] >= 70 &]

I get an empty list back. What am I doing wrong?

POSTED BY: Ilona
2 Replies
Posted 9 years ago

Using the original points generation and flatten and then a Cases to extract the relevant list elements

points = Table[{racing, sport, 8*racing + 12*sport}, {racing, 0, 
   40}, {sport, 0, 60}]; points = 
 Partition[Flatten[points], 3]; Cases[points, {a_, b_, c_} /; 
  a + b >= 70]
POSTED BY: Paul Cleary

You should also use Flatten to make ' points ' list uniform. currently the 'points' list is not uniform in the sense that it has sequence of lists which contains further lists(nesting of lists).

e.g. lets cut short your example to clarify:

In[42]:= points = Table[{racing, sport, 8*racing + 12*sport}, {racing, 0, 2}, {sport,  0, 3}]
Out[42]= {
        {{0, 0, 0}, {0, 1, 12}, {0, 2, 24}, {0, 3, 36}}, 
        {{1, 0, 8}, {1, 1, 20}, {1, 2, 32}, {1, 3, 44}}, 
        {{2, 0, 16}, {2, 1, 28}, {2, 2, 40}, {2, 3, 52}}
        }

You can see 'points' contains 3 lists which further contains 3 more lists nested inside.This kind of nesting is the cause where you are getting empty list as output.

In[46]:= Select[points, #[[1]] + #[[2]] >= 2 &]
Out[46]= {}

Now Flatten function will remove unnecessary nesting which is not required in your example case.

In[48]:= fpoints = Flatten[points, 1]

Out[48]= {{0, 0, 0}, {0, 1, 12}, {0, 2, 24}, {0, 3, 36}, {1, 0, 
  8}, {1, 1, 20}, {1, 2, 32}, {1, 3, 44}, {2, 0, 16}, {2, 1, 28}, {2, 
  2, 40}, {2, 3, 52}}

Now Select can be applied on flattened list(I have used 2 instead of 70 just for clarification).

In[45]:= Select[fpoints, #[[1]] + #[[2]] >= 2 &]

Out[45]= {{0, 2, 24}, {0, 3, 36}, {1, 1, 20}, {1, 2, 32}, {1, 3, 
  44}, {2, 0, 16}, {2, 1, 28}, {2, 2, 40}, {2, 3, 52}}..
POSTED BY: Damanjit Singh
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract