Smple_V Smple_V - 2 years ago 102
Python Question

How to replace values in multidimensional array?

I am trying to get a multidimensional array working, where the user string is filled in the cell.
I have been searching for ways to update user values in the multidimensional array,a little nudge in the right direction would be great help

def createMultiArray(self,usrstrng,Itmval):
#creates a multidimensional array, where usrstrng=user input, Itmval=width
ArrayMulti=[[" " for x in range(Itmval)]for x in range(Itmval)]

# need to update user values, therefore accessing index to update values.
for row in ArrayMulti:
for index in range(len(row)):

for Usrchr in usrstrng:
row[index]= Usrchr
print "This is updated array>>>",ArrayMulti



current output that i am getting

This is updated array>>> [['s', 's', 's'], ['s', 's', 's'], ['s', 's', 's']]

what i am looking for

This is updated array>>> [['f', 'u', 'n'], ['s', ' ', ' '], [' ', ' ', ' ']]

the blank can be filled in with *

Answer Source

string.replace won't work, since it does not affect the original value.

>>> test = "hallo"
>>> test.replace("a", " ")
'h llo'
>>> test

Instead you need to access the list via the indexes:

for row in ArrayMulti:
    for index in range(len(row)):
        row[index] = "a"

If you provide a more precise question and add the output you want to achieve to the question, I can give you a more precise answer.

I scrapped the previous solution since it wasn't what you wanted

def UserMultiArray(usrstrng, Itmval):
    ArrayMulti=[[" " for x in range(Itmval)] for x in range(Itmval)]

    for index, char in enumerate(usrstrng):
        ArrayMulti[index//Itmval][index%Itmval] = char
    return ArrayMulti

>>> stack.UserMultiArray("funs", 3)
[['f', 'u', 'n'], ['s', ' ', ' '], [' ', ' ', ' ']]

This little trick uses the whole-number-division:

[0, 1 ,2 ,3 ,4] // 3 -> 0, 0, 0, 1, 1

and the modulo operator(

[0, 1 ,2 ,3 ,4] % 3 -> 0, 1, 2, 0, 1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download