Walrus Operator: NameError: free variable 'it' referenced before assignment in enclosing scope
Walrus Operator: NameError: free variable 'it' referenced before assignment in enclosing scope
我想像这样使用海象运算符创建一个列表:
myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
it := re.sub(PATTERN, "", i).strip() for i in myvar if len(it) > 0
]
我得到这个错误:
it := re.sub(PATTERN, "", i).strip() for i in myvar if len(it) > 0
NameError: free variable 'it' referenced before assignment in enclosing scope
另一方面,当我这样做时它起作用了:
myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
re.sub(PATTERN, "", i).strip() for i in myvar if len(re.sub(PATTERN, "", i).strip()) > 0
]
其中:
PATTERN = "\r|\t|\n"
有人可以帮忙吗?我不知道我在这里错过了什么
好的。我想我终于通过将其更改为解决了它:
myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
n for i in myvar if len(n := re.sub(PATTERN, "", i).strip()) > 0
]
我想像这样使用海象运算符创建一个列表:
myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
it := re.sub(PATTERN, "", i).strip() for i in myvar if len(it) > 0
]
我得到这个错误:
it := re.sub(PATTERN, "", i).strip() for i in myvar if len(it) > 0
NameError: free variable 'it' referenced before assignment in enclosing scope
另一方面,当我这样做时它起作用了:
myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
re.sub(PATTERN, "", i).strip() for i in myvar if len(re.sub(PATTERN, "", i).strip()) > 0
]
其中:
PATTERN = "\r|\t|\n"
有人可以帮忙吗?我不知道我在这里错过了什么
好的。我想我终于通过将其更改为解决了它:
myvar = tr_list[8].css('td ::text').extract()
item['myvar'] = [
n for i in myvar if len(n := re.sub(PATTERN, "", i).strip()) > 0
]