4
$\begingroup$

I have a nested list of numbers, something like satisfied = {{1, 5, 6, 2, 1, 2}, {1, 5,,8, 6}, ..., {5, 6, 1}} and I want to count the number of occurences of 1 in each list. I know there is 1000 of them.

I have tried

Do[Count[satisfied[[i]], 1], {i, 1000}]

since this works for one chosen list

Count[satisfied[[1]], 1]
$\endgroup$
2
  • 1
    $\begingroup$ To work with lists, refer to List Manipulation $\endgroup$
    – Bob Hanlon
    Nov 12, 2022 at 20:09
  • 1
    $\begingroup$ Cases[yourList, 1, Infinity] // Length $\endgroup$
    – user170231
    Nov 13, 2022 at 17:32

1 Answer 1

5
$\begingroup$

There is no need to use a loop like this in Mathematica. Use the Count function and just map it. You do not need to know the length of the list either.

lis = {{1, 5, 6, 2, 1, 2}, {1, 5, 8, 6}, {5, 6, 1}}
Count[#, 1] & /@ lis

Mathematica graphics

There are many other ways to do this in Mathematica.

$\endgroup$
3
  • $\begingroup$ Thank you. I am new to this $\endgroup$
    – Ka Pe
    Nov 12, 2022 at 20:07
  • 1
    $\begingroup$ Very nice. In addition, using the operator form of Count: Count[1]/@lis $\endgroup$
    – user1066
    Nov 12, 2022 at 20:20
  • $\begingroup$ @user1066 that is good also. I myself have not looked at operator forms so I do not know much about it. I should look at these one day. I know there are at least 10 different ways to do the same thing in Mathematica, so it is a matter of finding the best method to use. $\endgroup$
    – Nasser
    Nov 12, 2022 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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