[英]Why am I getting an UnboundLocalError even though I am just defining a variable?
def alphabet_war(airstrikes):
bombs = []
for i in range(len(airstrikes)):
bombs.append([])
for bomb in airstrikes:
bomb_index = index(bomb)
for index in range(len(bomb)):
if bomb[index] == "*":
bombs[bomb_index].append(index)
return bombs
I am getting a "UnboundLocalError: local variable 'index' referenced before assignment"
for line bomb_index = index(bomb)
.我收到"UnboundLocalError: local variable 'index' referenced before assignment"
行的bomb_index = index(bomb)
。
While I have seen many articles on this, including: https://careerkarma.com/blog/python-local-variable-referenced-before-assignment/ that is quite helpful.虽然我看过很多关于这方面的文章,包括: https : //careerkarma.com/blog/python-local-variable-referenced-before-assignment/ ,这很有帮助。
I am still struggling to understand why I am getting this error.我仍在努力理解为什么我会收到此错误。 I don't see how I am using it before assigning it locally?在本地分配它之前,我看不到我是如何使用它的? I thought all I am doing is defining bomb_index
我以为我所做的就是定义bomb_index
I have also tried changing it slightly to the more concise:我也尝试将其稍微更改为更简洁:
for bomb in airstrikes:
for index in range(len(bomb)):
if bomb[index] == "*":
bombs[index(bomb)].append(index)
But here for index(bomb)
I get a int object not callable error
但是这里对于index(bomb)
我得到一个int object not callable error
The issue is bomb_index = index(bomb)
, index
is not a defined name at that point of your code.问题是bomb_index = index(bomb)
, index
在您的代码的那个点不是定义的名称。
Presumably, what you want is to know what index bomb
has in airstrikes
.想必,你想知道airstrikes
有什么索引bomb
。 The wrong way to do this (still using list.index()
as you originally intended) is:执行此操作的错误方法(仍按list.index()
使用list.index()
)是:
bomb_index = airstrikes.index(bomb) # scans airstrikes at every iteration searching for bomb
The right way to do this is to enumerate the items in the list as you loop over them:正确的方法是在遍历列表时枚举列表中的项目:
for bomb_index, bomb in enumerate(airstrikes): # no need for searching, you loop and know the index of every item as you loop over them
for index in range(len(bomb)):
if bomb[index] == "*":
bombs[bomb_index].append(index)
In the line:在行中:
bomb_index = index(bomb)
index
is undefined, because its firstly declared by the for loop directly below it. index
未定义,因为它首先由它下面的 for 循环声明。 I think what you're trying to do here is loop trough list values and indices simultaneously.我认为您在这里尝试做的是同时循环遍历列表值和索引。 For this, you can use enumerate
:为此,您可以使用enumerate
:
lst = ['a', 'b', 'c']
for index, value in enumerate(lst):
print(index, value)
# Returns:
# 0 a
# 1 b
# 2 c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.