当前位置:
首页
文章
前端
详情

Python技巧之检查列表所有元素是否相等

方法有三:

  1. 将列表构造为集合,再判断长度

  2. 用一个元素与所有元素比较

  3. 比较列表第一个元素的个数和列表长度

    Pythonic ways of checking if all

    items in a list are equal:

    lst = ['a', 'a', 'a']

    len(set(lst)) == 1 True

    all(x == lst[0] for x in lst) True

    lst.count(lst[0]) == len(lst) True

    I ordered those from "most Pythonic" to "least Pythonic"

    and "least efficient" to "most efficient".

    The len(set()) solution is idiomatic, but constructing

    a set is less efficient memory and speed-wise.

三个方法的排序,语言地道性由高到低,效率由低到高。构造一个集合就是用内存换速度的。

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。