1

I have lists like {0, 1, 0, 3, 0, -t2, 0, -(1/t2), 0, 0, 0, 0} including zeros, non-zero integers, and times. I wonder how I get the position of all non-zero integers?

user174967
  • 93
  • 6
  • @MichaelE2 I have tried this method, which I saw from another post. But this method includes all the Times terms. – user174967 Oct 30 '21 at 03:08
  • 4
    Position[list, n_Integer /; n != 0]? – Michael E2 Oct 30 '21 at 03:35
  • @MichaelE2 Not working either. This one gave very weird results for Times. – user174967 Oct 30 '21 at 03:48
  • 2
    Forgot the level spec 1. – Michael E2 Oct 30 '21 at 03:51
  • Can t2 be zero? – Syed Oct 30 '21 at 05:06
  • The original example of lists could be confusing, so I just edited it. The lists are like {0, 1, 0, 3, 0, -t2, 0, -(1/t2), 0, 0, 0, 0}. What I want is the position of 1 and 3. – user174967 Oct 30 '21 at 22:05
  • @Syed For my data, t2 cannot be zero. These are indeterminate variables, which are saved as Times or possibly symbol. – user174967 Oct 30 '21 at 22:08
  • @MichaelE2 It works after adding the level spec 1. Thank you so much! Would you mind posting it as an answer so that I can accept it? Also, a possible explanation would be very appreciated. I am very new to Mathematica. – user174967 Oct 30 '21 at 22:22
  • Position[expr, pattern, 1] returns the positions of the elements of expr at level 1 that match pattern. The pattern n_Integer /; n != 0 matches integers that are nonzero. The elements of expr are scanned left to right. The named pattern n_Integer will match each integer at level 1 and assign the value to the symbol n; then, in the condition (\;), the symbol n in n != 0 corresponds to the matched integer; if n is nonzero, the condition evaluates to True and the integer n is considered to match the whole pattern. – Michael E2 Oct 31 '21 at 17:02

2 Answers2

0

Position[{0, 0, 0, 0, 0, -t2, 0, -(1/t2), 0, 0, 0, 0}, n_ /; n =!= 0, 1] // Rest

行跑F
  • 401
  • 2
  • 2
  • This gives the position of both integers and times. But I only want the position of integers. I just edited my post since the original example could be confusing. The lists are {0, 1, 0, 3, 0, -t2, 0, -(1/t2), 0, 0, 0, 0}. What I want is the position of 1 and 3. – user174967 Oct 30 '21 at 22:04
0

Position[{0, 1, 0, 3, 0, -t2, 0, -(1/t2), 0, 0, 0, 0}, n_Integer /; n != 0, 1]

This gives the following output: {{2}, {4}}

Which says that at positions 2 and 4 there are integers that are not 0. At positions 2 and 4 are the values 1 and 3.

Nate
  • 725
  • 3
  • 14