【问题标题】:How to replace values in multidimensional array?如何替换多维数组中的值?
【发布时间】:2016-08-07 23:16:33
【问题描述】:

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

  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

输入

  funs

我得到的当前输出

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

我在找什么

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

可以用*填空

【问题讨论】:

  • 你为什么要遍历usrstrng来替换空格字符?
  • @James 我试图用字符串的每个字符替换单元格的每个值
  • 但是一旦你替换,字符串中将不再有空格,因此后续对replace的调用将无济于事。
  • @dbliss 我已经更新了当前问题中的原始代码

标签: python python-2.7 python-3.x


【解决方案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)

编辑

你也可以这样做

[[usrstrng[i*Itmval + j] if len(urstring) > i*Itmval + j else ' ' for j in range(Itmval)] for i range(Itmval)]

【讨论】:

    【解决方案2】:

    string.replace 不起作用,因为它不会影响原始值。

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

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

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

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

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

    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

    【讨论】:

    • 的 Arraymulti 是一个多维数组,我用 " " 对其进行了初始化 ...现在我正在使用 for 循环将字符串的每个值放入后续单元格中
    • 参数是 UserMultiArray("hallo", 5)
    • @dbliss 感谢更新代码的简要说明可以看stackoverflow.com/questions/36665750/…
    • 谢谢它有点帮助,现在你怎么能指导我如何让最后的空单元格用像'*'这样的符号填充
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多