我遇到倒数第二个 'elif' 语句的问题,我收到 str 和 integers 的连接错误-> 有什么解释吗?我的理解是我在空字符串 next_row 中添加了一个字符串“R”。
具体的错误是“只能将str(而不是“int”)连接到str”
def triangle(row):
next_row = ''
for i in row:
if i == 'G' and (i + 1) == 'B':
next_row += 'R'
elif i == 'G' and (i + 1) == 'R':
next_row += 'B'
elif i == 'R' and (i + 1) == 'B':
next_row += 'G'
elif i == 'R' and (i + 1) == 'G':
next_row += 'B'
elif i == 'B' and (i + 1) == 'G':
next_row += 'R'
elif i == 'B' and (i + 1) == 'R':
next_row += 'G'
print(type(next_row))
return None
triangle("BRGGBRG")
答案 0 :(得分:0)
您的问题是 (i + 1)
。 Python 不知道该怎么办。
Python 无法解析 'A' + 1
。
我认为当您说 (i + 1)
时,您正在尝试查看 row
的下一次迭代。
相反,迭代 range(0, len(row))
。使用 row[i]
查看当前值,使用 row[i + 1]
查看下一个值。
def triangle(row):
next_row = ''
for i in range(0, len(row)):
if row[i] == 'G' and row[i + 1] == 'B':
next_row += 'R'
elif row[i] == 'G' and row[i + 1] == 'R':
next_row += 'B'
elif row[i] == 'R' and row[i + 1] == 'B':
next_row += 'G'
elif row[i] == 'R' and row[i + 1] == 'G':
next_row += 'B'
elif row[i] == 'B' and row[i + 1] == 'G':
next_row += 'R'
elif row[i] == 'B' and row[i + 1] == 'R':
next_row += 'G'
print(type(next_row))
return None
triangle("BRGGBRG ")
请注意,对最后一个值使用 row[i + 1]
会导致运行时错误,因为不会有下一个值。
答案 1 :(得分:0)
python 中的字符串是可迭代对象。
因此,当您在字符串对象上使用 for 循环时,变量 i
将是字符串中的每个字符。
您可能希望将 enumerate 与可迭代对象一起使用来获取索引。
def triangle(row):
next_row = ''
# index means the index of for loop
for index, i in enumerate(row):
if index+1 == len(row):
# Do Whatever you wnat to do with the lastest character
break
if i == 'G' and row[index + 1] == 'B':
next_row += 'R'
elif i == 'G' and row[index + 1] == 'R':
next_row += 'B'
elif i == 'R' and row[index + 1] == 'B':
next_row += 'G'
elif i == 'R' and row[index + 1] == 'G':
next_row += 'B'
elif i == 'B' and row[index + 1] == 'G':
next_row += 'R'
elif i == 'B' and row[index + 1] == 'R':
next_row += 'G'
return None