【问题标题】:Python - consecutive character eliminationPython - 连续字符消除
【发布时间】:2017-09-19 19:17:46
【问题描述】:

在 python 中,如果我有列表输入 = ['>', '', '', '>', ''] 和我不希望在列表中有连续重复元素。 例如,新列表将是 input = ['>', '', '', ' 我该如何为其编写代码?

我试过了

for i in input:
    if(i == i+1):
        delete(i+1)

但此代码适用于列表中的整数值。

欢迎提出建议。

【问题讨论】:

标签: python list char duplicates


【解决方案1】:

您很接近,但您必须遍历range。工作示例:

input = ['>', '<', '>', '<', '>', '>', '<', '<']
indexes_to_delete = []
for i in range(len(input)-1):
    if(input[i] == input[i+1]):
        indexes_to_delete.append(i+1)
for idx in reversed(indexes_to_delete):
    input.pop(idx)
print(input)  # outputs ['>', '<', '>', '<', '>', '<']

i 从 0 到 input 的长度减一,因为最后一个元素没有后续元素。 indexes_to_delete 存储要删除的索引,而不是直接删除它们,以避免通过input 更改迭代。最后,如果索引按顺序弹出,元素的位置会移动,因此下一个要删除的索引也必须移动;为了避免麻烦,请以相反的顺序弹出。

【讨论】:

    【解决方案2】:

    在迭代列表时不要修改它。最简单的方法是将其复制到新列表中。

    output = [input.pop(0)]
    while input:
        temp = input.pop(0)
        if not temp == output[-1]:
            output.append(temp)
    

    这可能不是最高效的解决方案,但您明白了。从列表中删除第一个元素,将其与您删除的最后一个元素(输出列表中的最后一个)进行比较,如果两者不同,则添加到输出列表中。重复直到您的原始列表为空。

    【讨论】:

      【解决方案3】:

      您可以使用itertools.groupby 轻松简洁地做到这一点。

      >>> data = ['>', '<', '>', '<', '>', '>', '<', '<']
      >>> [x for x, _ in itertools.groupby(data)]
      ['>', '<', '>', '<', '>', '<']
      

      【讨论】:

        【解决方案4】:

        这个解决方案怎么样,它更简洁。

        import copy
        import itertools
        
        l = ['>', '<', '>', '<', '>', '>', '<', '<']
        
        z = copy.deepcopy(l)[1:]
        
        [elem[0] for elem in itertools.izip_longest(l, z) if elem[0] != elem[1]]
        
        ['>', '<', '>', '<', '>', '<']
        

        【讨论】:

          【解决方案5】:

          简单循环:

          lst = ['>', '<', '>', '<', '>', '>', '<', '<']
          result = [lst[0]]
          
          for i in lst[1:]:
              if i != result[-1]:
                  result.append(i)
          
          print(result)
          

          输出:

          ['>', '<', '>', '<', '>', '<']
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-02-17
            • 1970-01-01
            • 2022-01-23
            • 1970-01-01
            • 1970-01-01
            • 2017-04-03
            相关资源
            最近更新 更多