下面的代码-后面是我的问题的描述;
ends_partial_dict = {
'PLAIN END' : 'PE',
'MPT' : 'MNPT',
'PE': 'PE',}
original_description = (r'Pipe SA-106 GR. B SCH 40 PE 24" WALL smls'.upper())
item_split = original_description.split()
返回:['PIPE', 'SA-106', 'GR.', 'B', 'SCH', '40', 'PE', '24"', 'WALL', 'SMLS']
def item_end_partial() :
not_found = True
for key in ends_partial_dict:
if key == item_split:
item_end_partial_1 = ends_partial_dict[key]
return (item_end_partial_1)
not_found = False
break
if not_found :
return ("What are ENDS?")
print(item_end_partial())
由于某些原因,它返回我的"if not_found"什么是ENDS?"而不是字典中'PE'的值。
我尝试了许多不同的方法来调整字典值和函数设置,但似乎没有任何工作。有人知道为什么这不是"PE"吗?
你的代码中有很多冗余,加上你应该将值传递给你的函数,而不是依赖于全局变量:
ends_partial_dict = {
'PLAIN END' : 'PE',
'MPT' : 'MNPT',
'PE': 'PE',}
original_description = r'Pipe SA-106 GR. B SCH 40 PE 24" WALL smls'.upper()
item_split = original_description.split()
# Returns: ['PIPE', 'SA-106', 'GR.', 'B', 'SCH', '40', 'PE', '24"', 'WALL', 'SMLS']
def item_end_partial(item_split, ends_partial_dict) :
for key in ends_partial_dict:
if key in item_split:
return ends_partial_dict[key]
return "What are ENDS?"
print(item_end_partial(item_split, ends_partial_dict))