if / elif和sequencecial if语句

时间:2015-11-10 00:24:02

标签: python list if-statement

很抱歉,如果这个问题是重复的,但由于我的英语不太好,我没有想出如何制定问题,我想了解一些关于ifelif的问题语句。

我正在进行一项练习,我必须从列表x中获取列表y中未找到的项目。这是一种比较两个列表中每个元素的方法。

我解决了这个问题,但我没有提到顺序if-elif语句背后的逻辑,例如:

我的工作代码:

def merge_2(xs, ys):
    """
      Return only those items that are present in the first list,
      but not in the second.
    """
    result = []
    x_index = 0
    y_index = 0

    while True:

        if x_index >= len(xs):
            return result

        if y_index >= len(ys):
            result.extend(xs[x_index:])
            return result


        if xs[x_index] < ys[y_index]:
            result.append(xs[x_index])
            x_index += 1
        elif xs[x_index] > ys[y_index]:
            y_index += 1
        else:
            x_index += 1


print(merge_2([1, 2, 3, 4, 12, 35, 46, 54, 58, 62, 78, 82, 94], [1, 2, 4, 5, 6, 9, 54, 68, 78, 82]))

结果是:[3, 12, 35, 46, 58, 62, 94]

不同的代码是:

def merge_2(xs, ys):
    """
      Return only those items that are present in the first list,
      but not in the second.
    """
    result = []
    x_index = 0
    y_index = 0

    while True:

        if x_index >= len(xs):
            return result

        if y_index >= len(ys):
            result.extend(xs[x_index:])
            return result


        if xs[x_index] < ys[y_index]:
            result.append(xs[x_index])
            x_index += 1
        if xs[x_index] > ys[y_index]:
            y_index += 1
        else:
            x_index += 1


print(merge_2([1, 2, 3, 4, 12, 35, 46, 54, 58, 62, 78, 82, 94], [1, 2, 4, 5, 6, 9, 54, 68, 78, 82]))

给出结果[3, 12, 46, 58, 94]

所以,我的问题是:如果他们看起来做同样的事情,为什么我的结果差异很大?

0 个答案:

没有答案