Two list operations in math

I have two list operations that I would like to ask for help. The way I implemented them is not very elegant, so I want to find out from you experts.

1) Suppose I have two lists, one as {{0,2,4},{1,3,2},{2,0,4}} , and the other is {{1,3,7},{2,4,6},{3,1,9}} . I want to either be based on the value, or based on some criterion for filtering through the first list, and then get the corresponding elements in the second. For example, based on a value other than zero, I want to get {{3,7},{2,4,6},{3,9}} . Based on a condition greater than 2, I want to get {{7},{4},{9}} .

2) I have a list, for example {{{1,2},{1,1}},{{1,3},{2,4}},{{1,2},{2,3}},{{1,4},{3,3}}} . I want to create {{{1,2},{{1,1},{2,3}}},{{1,3},{{2,4}}},{{1,4},{{3,3}}} . That is, I want to group these second list if the first element is the same. How can I do this in a beautiful way?

Thank you very much.

+4
source share
2 answers

For the first part you want Pick :

 In[27]:= Pick[{{1,3,7},{2,4,6},{3,1,9}},{{0,2,4},{1,3,2},{2,0,4}},_?Positive] Out[27]= {{3,7},{2,4,6},{3,9}} In[28]:= Pick[{{1,3,7},{2,4,6},{3,1,9}},{{0,2,4},{1,3,2},{2,0,4}},_?(#>2&)] Out[28]= {{7},{4},{9}} 

For GatherBy second question GatherBy you like best:

 In[29]:= x = GatherBy[{{{1, 2}, {1, 1}}, {{1, 3}, {2, 4}}, {{1, 2}, {2, 3}}, {{1, 4}, {3, 3}}}, First] Out[29]= {{{{1, 2}, {1, 1}}, {{1, 2}, {2, 3}}}, {{{1, 3}, {2, 4}}}, {{{1, 4}, {3, 3}}}} 

And then you can apply the rule to clean things up a bit:

 In[30]:= x /. l:{{a_, _}..} :> {a, Last /@ l} Out[30]= {{{1, 2}, {{1, 1}, {2, 3}}}, {{1, 3}, {{2, 4}}}, {{1, 4}, {{3, 3}}}} 
+11
source

As Michael said, Pick is definitely a way to go first.

In the second part, I would like to propose an alternative that allows you to do this on one line: SelectEquivalents . (I know, I promote myself more likely, but I use this function a lot.) To get the result you are looking for, simply enter

 In[1] := SelectEquivalents[ <list>, First, Last, {#1,#2}& ] Out[1]:= {{{1, 2}, {{1, 1}, {2, 3}}}, {{1, 3}, {{2, 4}}}, {{1, 4}, {{3, 3}}}} 

Internally, SelectEquivalents uses Reap and Sow , so First tags every element in <list> , Last converts that element to the form we want to use, and {#1, #2}& returns a list with elements of the form {Tag, {<items with that tag>}} . The advantage is that you can specify everything in one step to get what you want, without further conversions.

+3
source

Source: https://habr.com/ru/post/1342943/


All Articles