如何在Python中用文本替换2D数组中的值

3

如何用文本中的字母替换所有值等于1的值?

如果文本不能完全适应数组,如何自动生成与第一个数组相同的新数组,以便包含所有字符?

提前感谢。

text = "helloworldddd"
my_array = [ [0,1,1],[1,1,0],[1,0,0] ]

result expecting: generated arrays which contains all characters
my_array2 = [ [0,h,e],[l,l,0],[o,0,0] ]
my_array3 = [ [0,w,o],[r,l,0],[d,0,0] ]
my_array4 = [ [0,d,d],[d,1,0],[1,0,0] ]

2
你尝试了什么?将你的代码编辑到你的问题中。 - Patrick Artner
你为什么想要这样做? - jpp
1个回答

2
使用列表和复制时,您应该了解浅拷贝和深拷贝的区别,否则您只会复制列表的引用-而不是它的值。在此处了解更多: Python中的列表深拷贝 计算需要多少个重复很容易,计算模式中1的数量,将字符串长度除以这个数量并加上1(使用mod检查是否有余数)。
深度复制一个足够长的结果列表,并开始用字符替换“1”。
from itertools import chain  # chaining multiple lists together
import copy                  # deepcopying the array to decouple copies

def createArr(t:str,arr:list):
    """Puts each character of t on the 1s of arr, extends arr with itself as pattern"""

    ones = sum(1 if q==1 else 0 for n in arr for q in n) # how many 1 in pattern
    mult = len(t)//ones  # how many reps needed for our text?
    if len(t)%ones != 0:
        mult += 1

    # create sufficient space by deepcopying the pattern into a longer list
    rv = list(chain(*(copy.deepcopy(arr) for _ in range(mult))))

    # start in sublinst on index 0
    subidx = 0
    # replace the 1s
    for c in t:    # walk all characters
        # maybe advance sublist index - if no 1s left
        while 1 not in rv[subidx] and subidx<len(rv):
            subidx+=1
        sub = rv[subidx] # get sublist
        sub[sub.index(1)] = c  # replace first 1 with act. char

    return rv 


text = "helloworldddd"
my_array = [ [0,1,1],[1,1,0],[1,0,0] ]


print(createArr(text,my_array))

输出:

 [[0, 'h', 'e'], ['l', 'l', 0], ['o', 0, 0], 
  [0, 'w', 'o'], ['r', 'l', 0], ['d', 0, 0], 
  [0, 'd', 'd'], ['d', 1, 0],   [1, 0, 0]]

如果需要,您可以将其分成相等的部分,使用arr的长度进行分区。这些高排名的问题和它们的答案将告诉你如何操作:如何将列表分成平均大小的块?


请问您能否在这里解答一个类似的问题:https://dev59.com/kanka4cB1Zd3GeqPRaUP - Seirra
1
@Seirra [crunsh]ed你的数字。 - Patrick Artner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接