【问题标题】:Python subtract list of strings from another list of strings [duplicate]Python从另一个字符串列表中减去字符串列表
【发布时间】:2019-07-27 13:56:07
【问题描述】:

我想减去一个包含多个相同元素的字符串列表(因此集合操作没有用)。

例子:

C = ['A','B','B']
D = ['B']

我想要一种方法来做到这一点:

C - D = ['A','B']

到目前为止我得到的示例,但没有给出我想要的结果

[item for item in C if item not in D]
returns: ['A']

这里有一个更详细的例子来说明我想要什么:

C = ['A','B', 'A','A','B','B','B','X','B']

D = ['A','B','B','Y']

这就是我想要的结果:

C - D = ['A', 'A', 'B', 'B','B','X']

【问题讨论】:

标签: python string list list-comprehension


【解决方案1】:

您可以使用集合中的计数器:

from collections import Counter
C_D = [i for v,c in (Counter(C)-Counter(D)).items() for i in v*c] 

【讨论】:

    【解决方案2】:

    不使用任何库:

    output = [x for x in C if not x in D or D.remove(x)]
    
    //output: ['A', 'B']
    

    【讨论】:

    • 巧妙使用 remove() +1 的 None 返回
    • 这种方式似乎会以某种方式改变结果——如果我多次运行它,它会在结果中添加一个额外的 B。不知道会发生什么,但有些事情没有按照我的预期或希望进行。
    【解决方案3】:

    虽然 Alain T. 的方式还可以,但有更好的方式使用Counter

    from collections import Counter
    C = ['A','B','B']
    D = ['B']
    result = list((Counter(C) - Counter(D)).elements())
    

    【讨论】:

    • @jslatane 有区别,尽管在此示例中没有显示,因为每个元素的计数都是 1。为了显示差异,list(Counter(a=1, b=2)) == ['a', 'b']list(Counter(a=1, b=2).elements()) == ['a', 'b', 'b']
    【解决方案4】:

    你可以试试这个:

    C = ['A','B', 'A','A','B','B','B','X','B']
    D = ['A','B','B','Y']
    
    res = [ i for i in C ]
    
    for i in D:
      if i in C:
        res.remove(i)
    
    print(res)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多