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 arra
Solution 1:
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:
forrowin ArrayMulti:
for index inrange(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
Solution 2:
This should work, only you need to move through your string as long as you move through the matrix, you only need to know how many characters you use in the previous iterations
offset=0forrowin ArrayMulti:
if len(usrstrng) >offsetfor index inrange(len(row)):
if len(usrstrng) ==offset+ index
break
row[index] = usrstrng[offset+ index]
else:
break
offset+= len(row)
EDIT
you can also do this
[[usrstrng[i*Itmval + j] iflen(urstring) > i*Itmval + j else' 'for j in range(Itmval)] for i range(Itmval)]
Post a Comment for "How To Replace Values In Multidimensional Array?"