我有一个应该是相当直截了当的操作失败在ArcGIS Pro2.4,并无法为我的一生找出原因。
如果字段"assettype“包含搜索字符串的一部分,那么将assettype_groupup的值设置为我返回的值。
例如,如果"assetttype“包含字符串”Building维连连大",并且我测试它是否包含术语“住宅”,并计算为真,那么返回字符串“住宅”。
目前,代码似乎没有返回任何结果/没有效果,而且运行得太快( 3,000,000行2-3秒)。
如果我尝试一个三元语句,这意味着一次使用一个术语,它似乎工作得很好。我不想采用这种方法,因为if/elif的可能性最终可能是广泛的,而且我只想运行这个例程一次。
您能看到下面的设置有什么明显的问题吗?
#Target Field Name
assettype_groupup
#Expression
func(!assettype!)
# Code block
def func(input):
if 'Residential' in input:
return 'Residential'
elif 'Industrial/Utilities' in input:
return 'Industrial/Utilities'
elif 'Transport/Infrastructure' in input:
return 'Transport/Infrastructure'
elif 'Conservation/National Park' in input:
return 'Conservation/National Park'
elif 'Recreational/Open Space' in input:
return 'Recreational/Open Space'
elif 'Mixed Use' in input:
return 'Mixed Use'
elif 'Community Use' in input:
return 'Community Use'
elif 'Rural/Primary Production' in input:
return 'Rural/Primary Production'
elif 'Special Use' in input:
return 'Special Use'
elif 'Unknown' in input:
return 'Unknown'
else:
''发布于 2019-11-30 01:16:48
我不熟悉Python,但我对ArcGIS相当了解。
在Python中,您应该避免将变量或参数命名为与任何内置函数相同的变量或参数,input()是内置函数的名称。另外,最后一个else:之后的行应该是return ''。由于情况并非如此,如果没有匹配,您的函数将有效地返回None,而不是空字符串'' (假设这是您想要的)。
考虑到这一点,以下是编写避免上述两个问题的函数的更好方法:
TARGETS = (
'Residential',
'Industrial/Utilities',
'Transport/Infrastructure',
'Conservation/National Park',
'Recreational/Open Space',
'Mixed Use',
'Community Use',
'Rural/Primary Production',
'Special Use',
'Unknown',
)
# Code block
def func(info):
for target in TARGETS:
if target in info:
return target
else: # Nothing matched.
return ''一个更高级、更短、更快的方法是使用Python的re正则表达式模块,该模块是其标准库的一部分:
import re
regex = re.compile('|'.join(map(re.escape, TARGETS)))
# Code block
def func(info):
mo = regex.search(info)
return mo.group(0) if mo else ''在Python中,可以通过使用3.8.0+ (又名"walrus“操作符)的佩普572新语法对赋值辅助表达式进行更短的缩短,该语法是从该版本开始添加的:
import re
regex = re.compile('|'.join(map(re.escape, TARGETS)))
def func(info):
return mo.group(0) if (mo := regex.search(info)) else '' # Py 3.8.0+https://stackoverflow.com/questions/59112262
复制相似问题