6
$\begingroup$

I am trying to take elements from a list of tuples using 2 criteria. An example of the list is:

list={{-1, -1}, {-1, 1}, {1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

And I need to take the elements that contain one value $=1$ and a second value $\neq1$. Thus at the end, I will have

    list2={{-1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

I`ve been trying using select as

list2 = Flatten[Table[Select[list[[i]], # == 1 &, 2]], {i, 1,5}], 1];

but the problem is that the values $=1$ do not have a "fixed column". Is there a way to do this avoiding an "if" statement?. Thanks in advance.

$\endgroup$
7
$\begingroup$
Select[list, Count[#, 1] == 1&]

{{-1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

Also

Pick[list, Lookup[Counts /@ list, 1, 0], 1]

{{-1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

And alternative ways to use Cases:

Cases[{OrderlessPatternSequence[1, Except[1]]}]@list
Cases[_?(Counts[#][1] == 1&)]@list

{{-1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

$\endgroup$
  • $\begingroup$ Oh, Thanks!. Do you know if the "Select" case can be used as a list?, eg, list[[i]]. This, because I have to track with the case, was not eliminated, For example, at the end, I will have element2-{-1,1} $\endgroup$ – mors May 22 at 15:08
  • $\begingroup$ @mors, the output from all methods is a list.So, using selected = Select[list, Count[#, 1] == 1&], you can access its parts as, say, selected[[2]] (which is {1, -1}) and selected[[2]] - {-1,1} gives {2, -2}. $\endgroup$ – kglr May 22 at 15:20
  • $\begingroup$ Thank you, I said it because every element in list is the output of a matrix, so my final goal is to construct llist2with the elements that were not erased from list and the name of the matrix that they correspond. e.g list2={{mat2-{1-1}, mat3-{-1,1}]. So I was wondering if I can use something as list2 = Flatten[ Table[ToString[ tabmatrices[[i]] <> "-" <> ToString[ Select[list[[i]], Count[#, 1] == 1&] ]], {i, 1,5}], 1]; $\endgroup$ – mors May 22 at 16:07
5
$\begingroup$

You could use Cases instead:

Cases[list, {1,Except[1]}|{Except[1],1}]

{{-1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

$\endgroup$
4
$\begingroup$

Paranoid version of kglr's Count solution:

Select[list, Total[Boole[PossibleZeroQ[# - 1]] & /@ #] == 1 &]

{{-1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}

$\endgroup$
3
$\begingroup$

You can also use the following construction:

 lst = {{-1, -1}, {-1, 1}, {1, 1}, {1, -1}, {1, (1 + I)/Sqrt[2]}}
 Cases[lst, {x_, y_} /; (x == 1 && y != 1) || (y == 1 && x != 1)]

Which may be more helpful in certain situations.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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