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
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]= Usrchrprint "This is updated array>>>",ArrayMulti
Input
funs
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 *
string.replace won't work, since it does not affect the original value.
>>> test = "hallo"
>>> test.replace("a", " ")
'h llo'
>>> test
'hallo'
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] = charreturn 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(https://en.wikipedia.org/wiki/Modulo_operation):
[0, 1 ,2 ,3 ,4] % 3 -> 0, 1, 2, 0, 1