能否请您告诉我为什么在代码中找不到num
:
from collections import defaultdict
import re
result = defaultdict(list)
for l in my_list:
k = None
for v in l:
if v in keywords:
k = v
if re.match(r'[0-9,.]+$', v):
num = v
if k is not None:
result[k].append(num)
错误:
> --------------------------------------------------------------------------- NameError Traceback (most recent call
> last) <ipython-input-84-31a1ed6e427e> in <module>
> 12 num = v
> 13 if k is not None:
> ---> 14 result[k].append(num)
> 15
>
> NameError: name 'num' is not defined
我无法理解此错误。
答案 0 :(得分:1)
在您的代码中,num = v
并不总是执行,只有在if条件为True
时才运行。首先用一个零值初始化num
,它将解决错误。
from collections import defaultdict
import re
result = defaultdict(list)
num = 0
for l in my_list:
k = None
for v in l:
if v in keywords:
k = v
if re.match(r'[0-9,.]+$', v):
num = v
if k is not None:
result[k].append(num)
答案 1 :(得分:0)
仅当您的陈述为真时才创建变量:
if re.match(r'[0-9,.]+$', v):
num = v
如果语句不正确,则不会创建该变量。
答案 2 :(得分:0)
很简单:
from collections import defaultdict
import re
result = defaultdict(list)
for l in my_list:
k = None
for v in l:
if v in keywords:
k = v
if re.match(r'[0-9,.]+$', v): # Here is an if statement, and num only gets defined if the condition meets it
num = v
if k is not None:
result[k].append(num)
如果我评论过的if
语句从未满足,则num
永远不会被定义。
答案 3 :(得分:0)
我已在下面的代码中添加了注释。 “ if条件”从未为真,因此变量num
从未初始化。
if re.match(r'[0-9,.]+$', v): # this if condition never got true
num = v # the initialization never executed
检查“ re.match()” documentation也是一个好主意。\
为什么“如果条件”永远不成立,是因为在代码中您从未在字符类中包含“ $”。
if re.match(r'[0-9,.]+$', v): # the $ should be inside [0-9,.,$]
num = v
'$' is usually a metacharacter, but inside a character class it’s stripped of its special nature。 我尝试了自己的字符串。
import re
String = "0,1,2,3,4,5,6,7,8,9,.,$"
if re.match(r"[0-9,.,$]", String):# $ should be inside character class
print("matched") # this print statement executes output is `matched`
else:
print("not matched")
我的代码输出显示matched