我无法获得简单的代码块,希望有人能发现错误。我觉得我是盲目的。
1)我创建了一个名为" SpeedLimit"的新短整数字段。在我的ArcGIS属性表中,表示道路类型的速度限制。
2)道路类型是在字段中找到的字符串" fclass"在同一张桌子里。
我打开SpeedLimit字段的字段计算器并填写以下内容:
逻辑前脚本代码:
def Speed(class):
if (class == ‘secondary’ or class == ‘tertiary’ or class == ‘trunk’ or class == ‘motorway’ or class == ‘primary’):
return 70
elif (class == ‘secondary_link’ or class == ‘tertiary_link’ or class == ‘trunk_link’ or class == ‘motorway_link’ or class == ‘primary_link’):
return 45
elif (class == ‘service’ or class == ‘track_grade1’ or class == ‘track_grade2’ or class == ‘track_grade3’ or class == ‘track_grade4’ or class == ‘track_grade5’):
return 15
else:
return 30
SpeedLimit =
Speed(!fclass!)
有人能发现我在接收语法错误时遇到的错误吗?
根据评论进行编辑: 我收到的错误是运行更简单的代码:
def Speed(road):
if (road == 'secondary'):
return 70
else:
return 30
**答案** 我根本没有选择" Python"单选按钮... 谢谢大家的帮助。
答案 0 :(得分:1)
class
是Python中的保留字,因此您应为参数选择其他名称,例如cls
。此外,我不确定这是您的代码中的真正问题还是只是复制粘贴到SO问题,引号字符为'
,而不是‘
。如果我们把它们放在一起,这段代码应该可以正常工作:
def speed(cls):
if (cls == 'secondary' or cls == 'tertiary' or cls == 'trunk' or cls == 'motorway' or cls == 'primary'):
return 70
elif (cls == 'secondary_link' or cls == 'tertiary_link' or cls == 'trunk_link' or cls == 'motorway_link' or cls == 'primary_link'):
return 45
elif (cls == 'service' or cls == 'track_grade1' or cls == 'track_grade2' or cls == 'track_grade3' or cls == 'track_grade4' or cls == 'track_grade5'):
return 15
else:
return 30
答案 1 :(得分:1)
你可能想要这个:
def speed(aClass):
if (aClass == 'secondary' or aClass == 'tertiary' or aClass == 'trunk' or aClass == 'motorway' or aClass == 'primary'):
return 70
elif (aClass == 'secondary_link' or aClass == 'tertiary_link' or aClass == 'trunk_link' or aClass == 'motorway_link' or aClass == 'primary_link'):
return 45
elif (aClass == 'service' or aClass == 'track_grade1' or aClass == 'track_grade2' or aClass == 'track_grade3' or aClass == 'track_grade4' or aClass == 'track_grade5'):
return 15
else:
return 30
fclass = 'tertiary_link'
print(speed(fclass))
但是在Python中更优雅:
def speed(aClass):
if aClass in ['secondary',
'tertiary',
'trunk',
'motorway',
'primary']:
return 70
if aClass in ['secondary_link',
'tertiary_link',
'trunk_link',
'motorway_link',
'primary_link']:
return 45
if aClass in ['service',
'track_grade1',
'track_grade2',
'track_grade3',
'track_grade4',
'track_grade5']:
return 15
else:
return 30
fclass = 'tertiary_link' # Only for testing
print(speed(fclass))
请注意,我使用elif
代替if
,因为每个分支都会返回一个值(因此会跳过下一个语句)。