我正在尝试添加 * 作为矩形字符矩阵的边框。例如,
["abc", "ded"]
应该返回
["*****","*abc*","*ded*","*****"]
我所做的是创建一个比原始矩阵多 2 行和 2 列的新矩阵,并用 * 填充它。所以问题是当我用原来的字母替换里面的 * 时,我有一个超出索引的错误。我不太明白为什么?
def addBorder(picture):
m=len(picture) #number of rows
n=len(picture[0]) #num of columns
newpic=[['*'*(n+2)]for y in range(m+2)]
for x in range(1,m+1):
for y in range(1,n+1):
newpic[x][y]=picture[x-1][y-1]
return newpic
请您参考如下方法:
字符串是不可变的,因此您不能“编辑”其中的单个字符,而是将其编入索引 - 这就是您在 for x ..: for y: ... 循环中尝试的内容。
要保留大部分代码,您可以将其更改为:
def addBorder(picture):
m=len(picture) #number of rows
n=len(picture[0]) #num of columns
newpic=[['*'*(n+2)]for y in range(m+2)]
for idx,text in enumerate(picture): # get text and index here
newpic[idx+1] = '*' + text+ '*' # change text in +1 row in target list
return newpic
print(addBorder( ["abc", "ded"]))
输出:
[['*****'], '*abc*', '*ded*', ['*****']]
更改更多代码:
def addBorder(picture):
# slightly more compley length computation, will work for ragged text as well
maxL = max(len(x) for x in picture)
patt = "*{:<"+str(maxL)+"}*" # left justified by maxL , see link below
rv = []
rv.append('*'*(maxL+2)) # top border
for t in picture:
rv.append(patt.format(t)) # text + adornment
rv.append('*'*(maxL+2)) # bottom border
return rv
print(addBorder( ["abc", "defgh","i"]))
输出:
['*******',
'*abc *',
'*defgh*',
'*i *',
'*******']
链接:string format mini language
您的超出索引错误消息有些误导 - 您在列表的范围内,但您正试图操纵字符串 - 我本以为
'str' 对象不支持项目assignment 在这里更合适......
编辑:参见 Azats answer为什么会出现错误 - 我留下了文字,这样他的帖子就不会丢失它的引用。
