我在Python函数中有以下代码:
strings = ('TIRS10', 'TIRS11')
if any(string in fields for string in strings):
def transform(row):
'''
Transform an input row in to a named tuple, then feed it in to a
dictionary.
'''
# split row in elements
elements = row.split('|')
# key: 1st column, replace
key = replace_dot_comma_space(elements[0])
# namedtuple
ect = namedtuple(key, [fields[0], fields[1]])
# feed namedtuples
ect.TIRS10 = is_number(elements[1])
ect.TIRS11 = is_number(elements[2])
# feed dictionary
dictionary[key] = dictionary.get(key, ect)
strings = ('b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7')
if any(string in fields for string in strings):
def transform(row):
'''
Transform an input row in to a named tuple, then feed it in to a
dictionary.
'''
# split row in elements
elements = row.split('|')
# key: 1st column, replace
key = replace_dot_comma_space(elements[0])
# *** small modification for the CWV field ***
fields[0] = 'cwv'
# named tuples
cwv = namedtuple(key,
[replace_dot_comma_space(fields[0]),
replace_dot_comma_space(fields[1]),
replace_dot_comma_space(fields[2]),
replace_dot_comma_space(fields[3]),
replace_dot_comma_space(fields[4]),
replace_dot_comma_space(fields[5]),
replace_dot_comma_space(fields[6]),
replace_dot_comma_space(fields[7]),
replace_dot_comma_space(fields[8]),
replace_dot_comma_space(fields[9])])
# feed named tuples
cwv.subrange = to_tuple(elements[1])
cwv.b0 = is_number(elements[2])
cwv.b1 = is_number(elements[3])
cwv.b2 = is_number(elements[4])
cwv.b3 = is_number(elements[5])
cwv.b4 = is_number(elements[6])
cwv.b5 = is_number(elements[7])
cwv.b6 = is_number(elements[8])
cwv.b7 = is_number(elements[9])
cwv.rmse = is_number(elements[10])
dictionary[key] = dictionary.get(key, cwv) # feed dictionary
map(transform, rows)
return dictionary
我得到了一个从xxx [F811] 行重新定义未使用的'transform'。我如何解决这个“错误”,以便不使用两个不同的功能,但只使用一个,稍后在同一个功能内?处理这种情况的正确方法是什么?
答案 0 :(得分:2)
一种方法是将它们命名为transform1和transform2,并将map放在if-else:
中if condition1:
transform = transform1
else: # if condition2
transform = transform2
map(transform, row)
此外,重用像字符串这样的变量并不好:它可能会引入细微的错误。隐含地更改字典变量也不好。明确地传递这些东西并且明确地返回更改的对象总是更好。
如果有如上所述的更多变换,重构更清晰的是面向对象的样式,其中.transform()是tirs-class或b-class的方法。然后字典自然是属性,是Transformer类状态的一部分,而不是全局属性。