【问题标题】:Python string lists: How does one retrieve the unique values from the comparison of two lists of strings?Python 字符串列表:如何从两个字符串列表的比较中检索唯一值?
【发布时间】:2013-02-07 10:33:41
【问题描述】:

我有 2 个长度不等、未排序的字符串列表,我想检索较长列表中唯一的值。我使用的真实列表包含数千个值。 listA 中存在的值总是在 listB 中找到。所有值只能在给定列表中找到一次。

例子:

listA = ['b0001', 'b0003', 'b0007', 'b0004'] listB = ['b0001', 'b0005', 'b0007', 'b0017', 'b0004', 'b0003', 'b0002', 'b0432']

预期结果:

listC = 'b0005', 'b0017', 'b0002', 'b0432']

我尝试使用 set 函数和交集或 enumerate 函数,但最终得到错误...

感谢您的帮助

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    更合适的方法是使用集合。

    setA = set(listA)
    setB = set(listB)
    listC = list(setB - setA)
    

    这里的减号表示集合 B 和 A 之间的差异。

    最好的问候

    【讨论】:

      【解决方案2】:

      使用列表推导:

      >>> listC = [item for item in listB if item not in listA]
      >>> listC
      ['b0005', 'b0017', 'b0002', 'b0432']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-07
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        相关资源
        最近更新 更多