【问题标题】:Unique elements inside lists of list列表列表中的唯一元素
【发布时间】:2017-04-12 16:21:10
【问题描述】:

如果我有一个嵌套列表,例如:

l = [['AB','BCD','TGH'], ['UTY','AB','WEQ'],['XZY','LIY']]

在这个例子中,'AB' 是前两个嵌套列表所共有的。如何在两个列表中删除“AB”,同时保持其他元素不变?一般来说,如何从两个或多个嵌套列表中出现的每个嵌套列表中删除一个元素,以便每个嵌套列表都是唯一的?

l = [['BCD','TGH'],['UTY','WEQ'],['XZY','LIY']]

是否可以使用 for 循环来做到这一点?

谢谢

【问题讨论】:

    标签: list python-3.x duplicates unique


    【解决方案1】:
    from collections import Counter
    from itertools import chain
    
    counts = Counter(chain(*ls)) # find counts
    result = [[e for e in l if counts[e] == 1] for l in ls] # take uniqs
    

    【讨论】:

      【解决方案2】:

      一种选择是这样做:

      from collections import Counter
      counts = Counter([b for a in l for b in a])
      for a in l:
          for b in a:
              if counts[b] > 1:
                  a.remove(b)
      

      编辑:如果您想避免使用(非常有用的标准库)collections 模块(参见评论),您可以将上面的 counts 替换为以下自定义计数器:

      counts = {}
      for a in l:
          for b in a:
              if b in counts:
                  counts[b] += 1
              else:
                  counts[b] = 1
      

      【讨论】:

      • 有没有不涉及进口的方式?
      • 我不知道你为什么会这样做; collections 在标准库中,您可能会希望它在您的工具箱中。无论如何,我用替代方法更新了答案。
      • 我只是一个初学者,我还没有学习任何导入模块
      【解决方案3】:

      一个没有导入的简短解决方案是首先创建原始列表的 reduced 版本,然后遍历原始列表并删除计数大于 1 的元素:

      lst = lst = [['AB','BCD','TGH'], ['UTY','AB','WEQ'],['XZY','LIY']]
      
      reduced_lst = [y for x in lst for y in x]
      
      output_lst = []
      
      for chunk in lst:
          chunk_copy = chunk[:]
          for elm in chunk:
              if reduced_lst.count(elm)>1:
                  chunk_copy.remove(elm)
          output_lst.append(chunk_copy)
      
      
      print(output_lst)
      

      应该打印:

      [['BCD', 'TGH'], ['UTY', 'WEQ'], ['XZY', 'LIY']]
      

      我希望这证明有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-26
        • 2011-05-23
        • 2023-03-31
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多