如何用文本中的字母替换所有等于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] ]
答案 0 :(得分:2)
使用列表和复制,您应该阅读浅层和深层复制的区别,否则您只需复制列表引用 - 而不是值。在此处阅读更多内容:Deep copy a list in Python
计算你需要多少重复是很容易的,计算模式中的1的数量,除以字符串的长度,并添加1
以获得良好的度量(整数除法是floor_division),如果它将与休息分开(用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的长度分成相等的部分,这个排名很高的问题及其答案会告诉你如何:How do you split a list into evenly sized chunks?