【发布时间】:2019-07-14 01:22:42
【问题描述】:
我是 python 新手,我有这个项目我正在做一个小项目,它有两个函数,第一个函数返回第一次在字符串中发现差异的索引。下一个函数执行此操作,但在字符串列表中。现在,由于我是业余爱好者,我使用了过多的 if 和 else 语句,导致返回语句过多,尤其是在第二个函数中,我得到了错误 [R1710:consistent-return-statements]。我该如何解决它,任何人都可以给我清晰的例子来更好的代码吗?抱歉问题拖了这么久。
IDENTICAL = -1
def singleline_diff(line1, line2):
"""
Inputs:
line1 - first single line string
line2 - second single line string
Output:
Returns the index where the first difference between
line1 and line2 occurs.
Returns IDENTICAL if the two lines are the same.
"""
len1 = len(line1)
len2 = len(line2)
minimum_length = min(len1, len2)
if len1 != len2:
if minimum_length == 0:
return 0
for idx in range(minimum_length):
if line1[idx] == line2[idx]:
pass
else:
return idx
return idx + 1
for idx in range(len1):
if line1[idx] == line2[idx]:
pass
else:
return idx
return IDENTICAL
def multiline_diff(lines1, lines2):
"""
Inputs:
lines1 - list of single line strings
lines2 - list of single line strings
Output:
Returns a tuple containing the line number (starting from 0) and
the index in that line where the first difference between lines1
and lines2 occurs.
Returns (IDENTICAL, IDENTICAL) if the two lists are the same.
"""
line_no = singleline_diff(lines1, lines2)
len_lines1, len_lines2 = len(lines1), len(lines2)
if len_lines1 == len_lines2:
if (len_lines1 or len_lines2) == 0:
if len_lines1 == len_lines2:
return (IDENTICAL, IDENTICAL)
else:
idx = singleline_diff(lines1[line_no], lines2[line_no])
return (line_no, idx)
else:
idx = singleline_diff(lines1[line_no], lines2[line_no])
if line_no == IDENTICAL:
return (IDENTICAL, IDENTICAL)
elif line_no != IDENTICAL:
return (line_no, idx)
else:
return (line_no, 0)
【问题讨论】:
-
你能提供一些你的代码失败的例子吗?
-
line_no = singleline_diff(lines1, lines2)。而且这个函数不需要两个字符串而不是字符串列表吗? -
它没有失败,它工作得很好,但它不是干净的,函数 multiline_diff pylint 返回 [R1710:不一致返回语句]
-
是的,但它需要字符串列表并返回存在差异的列表项的索引