我正在编写一个简单的python程序,使用双循环打印出一个带有一组唯一坐标的html页面。我收到错误,因为它无法识别循环中的变量(跨越+ node_counter)。我该怎么做才能获得在顶部声明的变量?
game_counter = 0
across0 = '72,70,97,70,97,61,116,71,97,83,97,75,72,75'
across1 = '143,70,168,70,168,61,187,71,168,83,168,75,143,75'
across2 = '212,70,237,70,237,61,256,71,237,83,237,75,212,75'
across3 = '283, 70, 308, 70, 309, 61, 327, 71, 308, 83, 308, 75, 283, 75'
while game_counter <60:
text_file.write("<!-- These are the image maps for game " + str(game_counter) + " -->\n\n")
node_counter = 0
while node_counter < 15:
placeholder_string = ""
placeholder_string += '<area shape="poly" coords = "' + (across + node_counter) + '" href="#"/>\n'
text_file.write(placeholder_string)
node_counter += 1
if node_counter == 15:
game_counter += 1
答案 0 :(得分:1)
看起来你正试图迭代你的“跨越”变量。也许你的意思是这样的:across = ['72...', '143...']
。然后,您可以使用across
循环遍历for
:
for a in across:
print(a)
我使用print
作为for
循环的示例。此外,如果您使用的是python 2,则可以使用print a
代替print(a)
。
答案 1 :(得分:0)
我认为您的意思是添加across0
,across1
,across2
和across3
,而不仅仅是across
另外,您不需要那些continue
语句。
答案 2 :(得分:0)
您正在尝试将变量across
添加到node_counter
,但您只定义了变量across0
,across1
,...这就是您获取变量的原因错误。
还有一些其他错误
across
更改要game_counter
的索引。if
行,因此您将陷入无限循环。将game_counter增量移到内循环之外。这给出了以下代码
across = [[72,70,97,70,97,61,116,71,97,83,97,75,72,75],
[143,70,168,70,168,61,187,71,168,83,168,75,143,75],
[212,70,237,70,237,61,256,71,237,83,237,75,212,75],
[283, 70, 308, 70, 309, 61, 327, 71, 308, 83, 308, 75, 283, 75]]
while game_counter < len(across):
text_file.write("<!-- These are the image maps for game " + str(game_counter) + " -->\n\n")
node_counter = 0
while node_counter < len(across[game_counter]):
placeholder_string = ""
placeholder_string += '<area shape="poly" coords = "' + (across[game_counter][node_counter] + node_counter) + '" href="#"/>\n'
text_file.write(placeholder_string)
node_counter += 1
game_counter += 1
但是你可能会更好地使用for循环,至少对于内循环:
for item in across[game_counter]:
...
... (item + node_counter) ...