【问题标题】:Python: Comparing Two listsPython:比较两个列表
【发布时间】:2016-03-16 19:38:09
【问题描述】:

我正在尝试使用 Python 比较这两个列表:

comp1 = [['set',1,2]]
comp2 = [['set',2,1]]

两者都是集合 {1,2} 的有效表示

我本质上想检查这些列表 comp1 和 comp2 是否彼此相等,但我不确定如何在 Python 中执行此操作。

我也有兴趣了解如何使用以下列表来做到这一点:

comp3 = [['set',1,2],['set',3,4]]
comp4 = [['set',2,1],['set',4,3]]

【问题讨论】:

    标签: python list set compare


    【解决方案1】:
    comp3 = [set(L[1:]) for L in comp3]
    comp4 = [set(L[1:]) for L in comp4]
    
    comp3 == comp4  # this should do the trick
    

    【讨论】:

    • 我试过这个,但我得到 TypeError: unhashable type: 'list' 尝试运行它时
    【解决方案2】:

    只是为了好玩,如果您希望通过第一个字符串推断类型。您可以从__builtin__ 模块中获取它。

    def typify(seq):
        seq = iter(seq)
        typestr = next(seq)
        return getattr(__builtin__, typestr)(seq)
    
    comp3 = list(map(typify, comp3))
    

    该函数接受第一个参数,从__builtin__ 模块中找到等效类型,并将其应用于序列的其余部分。 然后我们可以map这个函数对你列出comp3的所有子元素。 在 python2 上 map 会返回一个列表,而在 python3 中你必须显式地转换它,否则它只会给你一个生成器。

    这足够通用,因此如果您传递不同的类型,它会自动识别它:

    comp3 = [['list',1,2],['set',3,4]]
    list(map(typify, comp3))
    #[[1, 2], {3, 4}]
    

    之后你就可以做

    comp3 = [['set',1,2],['set',3,4]]
    comp4 = [['set',2,1],['set',4,3]]
    
    comp3 = list(map(typify, comp3))
    comp4 = list(map(typify, comp4))
    
    comp3 == comp4
    

    【讨论】:

    • 这很酷,我从来没有意识到我可以从__builtin__getattr 哈哈,想过用eval 做点什么,但这可能会导致灾难
    • 它总是依赖于源...如果你从外部获取数据是的,那会很危险,但如果你是源,eval 可以用于非内置类喜欢OrderedDict 或类似的
    【解决方案3】:

    这种方法怎么样(使用itertools.chain):

    >>> comp3 = [['set',1,2],['set',3,4]]
    >>> comp4 = [['set',2,1],['set',4,3]]
    >>> from itertools import chain
    >>> print set(chain(*comp3))
    set([3, 1, 2, 'set', 4])
    >>> set(chain(*comp3)) == set(chain(*comp4))
    True
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多