如何替换多维数组中的值?

2024-09-30 08:36:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让一个多维数组工作,其中用户字符串填充在单元格中。 我一直在寻找在多维数组中更新用户值的方法

  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

输入

^{pr2}$

我得到的电流输出

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

我在找什么

  This is updated array>>> [['f', 'u', 'n'], ['s', ' ', ' '], [' ', ' ', ' ']]
<>空白可以填入*


Tags: 用户inforindexisrange数组this
2条回答

在字符串。替换不会起作用,因为它不会影响原始值。在

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

相反,您需要通过索引访问列表:

^{pr2}$

如果您提供一个更精确的问题,并将您想要实现的输出添加到问题中,我可以给您一个更精确的答案。

我放弃了以前的解决方案,因为它不是你想要的

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', ' ', ' '], [' ', ' ', ' ']]

这个小技巧使用整数除法:

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

以及模运算符(https://en.wikipedia.org/wiki/Modulo_operation):

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

这应该行得通,只要你在矩阵中移动你的字符串,你只需要知道你在以前的迭代中使用了多少个字符

offset = 0
for row in ArrayMulti:
    if len(usrstrng) > offset
        for index in range(len(row)):
            if len(usrstrng) == offset + index
                break
            row[index] = usrstrng[offset + index]
    else:
        break
    offset += len(row)

编辑

你也可以这样做

^{pr2}$

相关问题 更多 >

    热门问题