【问题标题】:How to remove duplicate who are followed each other in a list如何删除列表中相互跟随的重复项
【发布时间】:2022-12-18 17:55:52
【问题描述】:

在列表中,我需要删除列表中彼此跟随的重复项 就像在这个例子中:

[("0", "1"), ("1", "2"), ("0", "2"), ("2", "0")]

和我想要的输出:

[("0", "1", "2", "0", "2", "0")]

我什么也没尝试,因为我不知道该怎么做,也许遍历列表并使用if index[0] == index[1]

【问题讨论】:

  • 为什么输出是一个包含单个元组的列表?
  • 另请注意,您的数据不是我们可以复制、粘贴和运行的有效 Python。你的报价不是正常的报价。使用专为不会使用那种奇特字符的编程而设计的编辑器。

标签: python list duplicates tuples


【解决方案1】:

使用一个简单的嵌套循环跟踪前一个元素:

l = [('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]

out = []
prev = None
for t in l:
    for x in t:
        if x != prev:
            out.append(x)
        prev = x
print(out)

输出:['0', '1', '2', '0', '2', '0']

如果您真的想要一个包含单个元组的列表:

out = [tuple(out)]

输出:[('0', '1', '2', '0', '2', '0')]

【讨论】:

    【解决方案2】:

    您可以在几个连续的步骤中执行此操作(实际上可以合并):

    tuplist = [('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]
    
    # unpacking tuples
    list2 = []
    for t in tuplist:
        list2 += [t[0], t[1]]
        
    # removing duplicates
    list3 = [list2[0]]
    for i in list2[1:]:
        if i != list3[-1]:
            list3.append(i)
            
    # converting list3 to the desired format
    list4 = [tuple(list3)]
    

    【讨论】:

    • 你也可以只是extendlist2t
    • 事实上,extend 是我忘记使用的方法之一;谢谢。
    【解决方案3】:

    你需要先展平你的列表(我用chain(*lst)做,然后你可以使用groupby来跳过连续的重复:

    from itertools import chain, groupby
    
    lst = [('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]
    ret = list(item for item, _ in groupby(chain(*lst)))
    
    print(ret)
    # ['0', '1', '2', '0', '2', '0']
    

    【讨论】:

      【解决方案4】:

      为了解决这个问题,可以使用for循环遍历元组列表,并使用if语句检查当前元组是否与前一个元组具有相同的第一个和第二个元素。如果是,则可以跳过当前元组,否则可以将其添加到新列表。这是一个如何工作的示例:

      # Original list of tuples
      tuples = [(‘0’, ‘1’), (‘1’, ‘2’), (‘0’, ‘2’), (‘2’, ‘0’)]
      
      # Create an empty list to store the non-duplicate tuples
      no_duplicates = []
      
      # Iterate over the tuples
      for i in range(len(tuples)):
        # Check if the current tuple has the same first and second elements as the previous tuple
        if i > 0 and tuples[i][0] == tuples[i-1][1] and tuples[i][1] == tuples[i-1][0]:
          # If they are the same, skip the current tuple
          continue
        else:
          # Otherwise, add the current tuple to the list of non-duplicates
          no_duplicates.append(tuples[i])
      
      # Print the list of non-duplicate tuples
      print(no_duplicates)
      

      此代码将产生以下输出:

      [(‘0’, ‘1’), (‘1’, ‘2’), (‘0’, ‘2’)]
      

      我希望这有帮助!

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2018-08-29
      • 2011-02-20
      • 2020-07-06
      相关资源
      最近更新 更多