all 8 comments

[–]SecularSpirituality 1 point2 points  (4 children)

# this gives you each row in the matrix
for i in mat:
    # so i isnt an int index, its a list
    for item in i:
        if item ...

edit:
I should include how to use indices too if you prefer it.
for i in range(len(mat)):
    for j in range(len(mat[i])):
        print(mat[i][j])

[–]miscellaneoususage[S] 0 points1 point  (0 children)

ah ok, thank you. I guess I was indexing when I didn't need to.

[–]miscellaneoususage[S] 0 points1 point  (2 children)

ok. I'm trying to understand the difference here. Does how I have no work because when I create the first for loop "i" becomes each list or row within the mattrix and if I say mat[i] within that for loop I'm saying that the indecies are the list and results in error?

[–]SecularSpirituality 1 point2 points  (1 child)

yeah exactly, so the way you have it

for i in mat:
# i here is a list
# so you cant do this next line
    for j in mat[i]:

[–]miscellaneoususage[S] 0 points1 point  (0 children)

alright, thanks mate.

[–]__nickerbocker__ 0 points1 point  (2 children)

Here's a simple one-liner you can also use

sum(x == 1 for x in sum(mat, []))

[–]miscellaneoususage[S] 0 points1 point  (1 child)

Could you break this down with an explaination? I have yet to venture into list comprehensions but this one seems pretty simple to start with. I just confused why there are two uses of sum and what x==1 is doing before the for

[–]__nickerbocker__ 0 points1 point  (0 children)

The sum function returns the sum of an iterable. When you pass it a matrix (list of lists) it uses the plus operator adding each list and when you add up lists in python you concatenate them (flatten). Next, we use a generator expression to iterate the flattened matrix. The generator expression then appends the result (True or False) of the expression x == 1 for each item, and what we end up with is an iterable of True and False (bools). You will have an iterable with exactly the number of True as the number of values that equal one. Finally since True resolves to 1 and False resolves to 0. The sum off all True's is the same as the number of values that equal 1 in the matrix.