【问题标题】:Loop through a sorted list and find the range that duplicates lie over遍历排序列表并找到重复项所在的范围
【发布时间】:2020-12-31 02:57:00
【问题描述】:

我正在尝试查找列表中重复的位置范围。 例如,在列表中l = [1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 5, 6,7,7, 7] 2 在位置 2 和 5 之间重复。我的代码一直工作到最后,错误是由我假设的内部循环没有跟踪数组的长度引起的。

我应该如何解决这个错误?

代码:

l = [1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 5, 6,7,7, 7]

i = 0
out = []
while i < (len(l)):
    ogPos = i
    ogVal = l[i]
    while (l[i] == ogVal):
        print(i)
        i += 1
    edPos = i-1
    print(f'\t{ogPos}\t{edPos}\t{ogVal}')

输出:

0
1
        0       1       1
2
3
4
5
        2       5       2
6
7
8
        6       8       3
9
        9       9       4
10
        10      10      5
11
        11      11      6
12
13
14
Traceback (most recent call last):
  File "testlist.py", line 8, in <module>
    while (l[i] == ogVal):
IndexError: list index out of range

【问题讨论】:

    标签: python list


    【解决方案1】:

    您不需要嵌套循环,使用for 循环可以更容易地跟踪您的代码。使用嵌套循环,您需要重复长度约束,但您可以只拥有一个 while 循环而没有重复约束:

    >>> l = [1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 5, 6,7,7, 7]
    >>> 
    >>> i = 0
    >>> out = []
    >>> ogPos = i
    >>> ogVal = l[i]
    >>> while i < len(l):
    ...     print(i)
    ...     if l[i] != ogVal:
    ...         edPos = i-1
    ...         ogPos = i
    ...         ogVal = l[i]
    ...         print(f'\t{ogPos}\t{edPos}\t{ogVal}')
    ...     i += 1
    ... 
    0
    1
    2
        2   1   2
    3
    4
    5
    6
        6   5   3
    7
    8
    9
        9   8   4
    10
        10  9   5
    11
        11  10  6
    12
        12  11  7
    13
    14
    

    不用在外循环中定义ogPosogVal,您可以在循环外定义它并在发现更改时重置它,而不是在数字相同时进行迭代。

    for循环版本稍微简单一些,只需将while替换为for i in range(len(l))即可:

    >>> l = [1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 5, 6,7,7, 7]
    >>> 
    >>> i = 0
    >>> out = []
    >>> ogPos = i
    >>> ogVal = l[i]
    >>> for i in range(len(l)):
    ...     print(i)
    ...     if l[i] != ogVal:
    ...         edPos = i-1
    ...         ogPos = i
    ...         ogVal = l[i]
    ...         print(f'\t{ogPos}\t{edPos}\t{ogVal}')
    ... 
    0
    1
    2
        2   1   2
    3
    4
    5
    6
        6   5   3
    7
    8
    9
        9   8   4
    10
        10  9   5
    11
        11  10  6
    12
        12  11  7
    13
    14
    

    【讨论】:

      【解决方案2】:

      由于内部循环前进i,它还应该检查它与列表的长度,就像外部循环一样:

      while i < (len(l)):
          ogPos = i
          ogVal = l[i]
          while (i < len(l) and l[i] == ogVal): # Here
              print(i)
              i += 1
          edPos = i-1
          print(f'\t{ogPos}\t{edPos}\t{ogVal}')
      

      【讨论】:

        猜你喜欢
        • 2020-09-07
        • 2021-04-07
        • 2021-10-25
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-28
        • 1970-01-01
        相关资源
        最近更新 更多