T
T
Timebird2018-06-04 12:33:15
Python
Timebird, 2018-06-04 12:33:15

Why is the loop value not being replaced?

The question is extremely dumb.
There is a mat matrix, it is necessary to replace numbers greater than mean by 1 and less than mean by 0.
I write:

def translate_mat(mat, mean):
  for row in mat:
    for elem in row:
      if elem < mean:
        elem == 0
      else:
        elem == 1
  return mat

I call:
translate_mat(mat, mean), at the output I get the original array without any replacements. Here it is possible not to fence list comprehensions, but somehow fix my loop so that it works?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-06-04
@Timebird

In addition to replacing == with =, there is one more thing: row is probably a list of numbers? Then the variable (or reference) elem does not refer to a specific position in the list, but simply to a number object. That is, it is "ELEM is the number X", but not "ELEM is the nth number from the list". When you write you don't replace the number in the list. You'll just say that elem now refers to the number object 1. Instead of "ELEM will now be the number Y", you need "The nth number from the list is now Y". To replace an element in the list, you need to write Let's rewrite the code:

def translate_mat(mat, mean):
  for row in mat:
    for i in range(len(row)):  
      if row[i] < mean:
        row[i] = 0
      else:
        row[i] = 1
  return mat

Another option:
def translate_mat(mat, mean):
  for row in mat:
    for i, elem in enumerate(row):  
        row[i] = 0 if elem < mean else 1
  return mat

P
PolinaRuRu, 2018-06-04
@PolinaRuRu

== - this is equal, that is, a test for whether it is equal.
= is an assignment.
you want to assign a new value, use =

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question