有没有简单的方法来比较python中的列表项?

 凡心悟事 发布于 2023-02-13 19:41

让我们说:

x= [2,2,2,2]
y= [2,1,2,2]

是否有任何简洁的方法来检查列表项是否全部相等.所以,我希望输出为:

x True
y False 

Steve Jessop.. 5

如果您关心性能并且列表可能很长:

all(item == x[0] for item in x)

一旦找到不相等的元素,它就会完成.请注意all返回True空序列,因此如果不是您想要的结果,则len(x)先测试.

Timings,故意操纵的案件支持我的回答:

$ python --version
Python 2.7.5

$ python -mtimeit "x = range(1000000)"
10 loops, best of 3: 18 msec per loop

$ python -mtimeit "x = range(1000000); all(item == x[0] for item in x)"
100 loops, best of 3: 19.2 msec per loop

$ python -mtimeit "x = range(1000000); all(item == x[0] for item in x[1:])"
10 loops, best of 3: 35.6 msec per loop

$ python -mtimeit "x = range(1000000); len(set(x)) == 1"
10 loops, best of 3: 72.7 msec per loop

通过"一点点",我只是意味着采取简单的步骤,以避免可能的大量不必要的工作和内存使用.如果你非常关心性能,因为这行代码非常关键,那么你可以做些什么来调整我的答案.首先想到的是避免在元素0处进行自我比较,但我不知道是否itertools.islice有足够低的开销来获得净胜利.你必须测试它.

2 个回答
  • 如果您关心性能并且列表可能很长:

    all(item == x[0] for item in x)
    

    一旦找到不相等的元素,它就会完成.请注意all返回True空序列,因此如果不是您想要的结果,则len(x)先测试.

    Timings,故意操纵的案件支持我的回答:

    $ python --version
    Python 2.7.5
    
    $ python -mtimeit "x = range(1000000)"
    10 loops, best of 3: 18 msec per loop
    
    $ python -mtimeit "x = range(1000000); all(item == x[0] for item in x)"
    100 loops, best of 3: 19.2 msec per loop
    
    $ python -mtimeit "x = range(1000000); all(item == x[0] for item in x[1:])"
    10 loops, best of 3: 35.6 msec per loop
    
    $ python -mtimeit "x = range(1000000); len(set(x)) == 1"
    10 loops, best of 3: 72.7 msec per loop
    

    通过"一点点",我只是意味着采取简单的步骤,以避免可能的大量不必要的工作和内存使用.如果你非常关心性能,因为这行代码非常关键,那么你可以做些什么来调整我的答案.首先想到的是避免在元素0处进行自我比较,但我不知道是否itertools.islice有足够低的开销来获得净胜利.你必须测试它.

    2023-02-13 19:43 回答
  • 好吧,你可以使用set:

    >>> len(set(x)) == 1
    True
    >>> len(set(y)) == 1
    False
    

    使用以下脚本查看,哪种方式最适合您:

    from timeit import timeit
    
    # All the same
    print timeit('len(set([2, 2, 2, 2])) == 1')
    # 0.843292317054
    
    # Not the same
    print timeit('len(set([2, 1, 2, 2])) == 1')
    # 0.869108628247
    
    ## Without set ##
    
    # AlL the same
    print timeit('all(item == x[0] for item in x)', setup='x = [2,2,2,2]')
    # 1.20339177387
    
    # Not the same
    print timeit('all(item == x[0] for item in x)', setup='x = [2, 1, 2, 2]')
    # 1.42827283125
    

    根据我的经验,使用set似乎是最快的方式.

    2023-02-13 19:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有