我正在尝试解决以下问题:
字符串“PAYPALISHIRING”在给定的行数上以锯齿形图案书写,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性)
P A H N
A P L S I I G
Y I R
然后逐行读取:“PAHNAPLSIIGYIR”
编写代码,该代码将采用字符串并在给定行数的情况下进行此转换:
字符串转换(字符串 s, int numRows);
我编写了以下代码,但在粗体行中出现错误 “TypeError:+ 不支持的操作数类型:'NoneType' 和 'unicode'”
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows==1:
return s
templist=[None]*numRows
ret=" "
curRow=0
goingDown=0
for each_char in s:
if templist[curRow]:
templist[curRow]=each_char
else:
**templist[curRow]=templist[curRow] + each_char**
if (curRow==numRow-1 or curRow == 0):
goingDown = not goingDown
if goingDown:
curRow=curRow+1
else:
curRow=curRow-1
for each_str in templist:
ret=ret+each_str
print ret
我在这方面做错了什么吗?如果有人能指出这里的问题那就太好了。 提前致谢
最佳答案
您的条件似乎在以下几行中颠倒过来:
if templist[curRow]:
templist[curRow]=each_char
else:
**templist[curRow]=templist[curRow] + each_char**
它可能应该是:
if templist[curRow]:
templist[curRow]=templist[curRow] + each_char
else:
templist[curRow]=each_char
这可以确保它仅在 templist[curRow]
中的字符串已存在(不是 None
)时才追加到该字符串,从而避免了添加字符串为None
。
更好的方法可能是设置 templist = [""] * numRows
,即空字符串列表,然后使用 templist[curRow] +=each_char< 添加到其中
,它始终有效,因为您可以向空字符串添加字符。
关于python - 尝试将字符附加到字符串时出现 "Unsupported operand type for +: NoneType",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240343/