How to change values of only one column in an array (PURE Python)

Asked

Viewed 349 times

0

I am doing a work of programming in PURE Python (that is, it is not allowed to use Pandas/Numpy) whose first part is, in an array, replace certain values by certain numbers.

For example: in the matrix

f s g t f f c
x f g t n f c
f y n t n f c

, I need to analyze each line and, in the first element of each line,

  • If element is "b", replace with 0;
  • If item is "c", replace by 1;
  • If element is "x", replace by 2;
  • among other specific letters, so on.

However, in the second element of each line, the rule of letters is different, I need to analyze other letters.

So I researched and tried to use Python’s List Comprehension:

for j in [x[0] for x in matriz]:
    if j == 'b':
        j = "0"
        j = int(j) # transforma string em inteiro
        
    elif j == 'c':
        j = "1"
        j = int(j)
        
    elif j == 'x':
        j = "2"
        j = int(j)
        

for j in [x[1] for x in matriz]:
    if j == 'f':
        j = "0"
        j = int(j)
        
    elif j == 'g':
        j = "1"
        j = int(j)
        
    elif j == 'y':
        j = "2"
        j = int(j)
        
    elif j == 's':
        j = "3"
        j = int(j)

But it didn’t work. I did a print of j in each if after it replaces the value, it shows the integer value, but does not substitute in the matrix, and so it remains the same.

  • The only condition is not to use libraries?

  • @Henriquehott yes, I cannot use modules or libraries other than the standard Python libraries.

  • Then I believe my answer is correct.

1 answer

1


What you can do is work with dictionary, because of key system: value.

It works well for several reasons, for example, the code is easier to read, as it does not have several if and elif.

Basically what happens is:

  1. Scroll through each matrix line:
for linha in matriz:
  1. Scroll through each letter of the line, using the range() function, as it will return the integer that allows you to access the value of the line in the correct way by enabling assignments:
for letra in range(len(linha)):
  1. After creating the loops, you have to test the condition, which in this case is: If the letter is in the dictionary. And if true, replace the list item with the value in the dictionary.
if linha[letra] in tradutor:
   linha[letra] = tradutor[linha[letra]]

Complete code:

matriz = [
    ['f', 's', 'g', 't', 'f', 'f', 'c'],
    ['x', 'f', 'g', 't', 'n', 'f', 'c'],
    ['f', 'y', 'n', 't', 'n', 'f', 'c']
]

tradutor = {'b': 0, 'c': 1, 'x': 2}

for linha in matriz:
    for letra in range(len(linha)):
        if linha[letra] in tradutor:
            linha[letra] = tradutor[linha[letra]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.