【问题标题】:Pythonic way to check that the lengths of lots of lists are the same检查大量列表长度是否相同的 Pythonic 方法
【发布时间】:2012-03-01 07:35:45
【问题描述】:

我有许多列表要在我的程序中使用,但我需要确保它们的长度相同,否则我稍后会在我的代码中遇到问题。

在 Python 中执行此操作的最佳方法是什么?

例如,如果我有三个列表:

a = [1, 2, 3]
b = ['a', 'b']
c = [5, 6, 7]

我可以这样做:

l = [len(a), len(b), len(c)]
if max(l) == min(l):
   # They're the same

有没有更好或更 Pythonic 的方式来做到这一点?

【问题讨论】:

    标签: python list if-statement


    【解决方案1】:
    len(set(len(x) for x in l)) <= 1
    

    后来我写完了:

    def some(x):
        """Replacement for len(set(x)) > 1"""
    
        if isinstance(x, (set, frozenset)):
           return len(x) > 1
    
        s = set()
        for e in x:
            s.add(e)
            if len(s) > 1:
                return True
        return False
    
    def lone(x):
        """Replacement for len(set(x)) <= 1"""
        return not some(x)
    

    上面的内容可以写成:

    lone(len(x) for x in l)
    

    一旦找到具有不同长度的列表,它将停止获取列表的长度。

    【讨论】:

    • 可以&lt;= 1处理l为空的情况...
    【解决方案2】:

    假设您有一个非空列表,例如

    my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]
    

    你可以使用

    n = len(my_list[0])
    if all(len(x) == n for x in my_list):
        # whatever
    

    这会短路,所以当遇到第一个长度错误的列表时,它将停止检查。

    【讨论】:

    • +1 表示最早可能退出my_list[1]...其他一些人缺少这个。
    【解决方案3】:

    对max 和min 的每次调用都会遍历整个列表,但您实际上并不需要这样做;您可以通过一次遍历检查所需的属性:

    def allsamelength(lst_of_lsts):
        if len(lst_of_lsts) in (0,1): return True
        lfst = len(lst_of_lsts[0])
        return all(len(lst) == lfst for lst in lst_of_lsts[1:])
    

    如果其中一个列表的长度与第一个不同,这也会短路。

    【讨论】:

      【解决方案4】:

      一点函数式 Python:

      >>> len(set(map(len, (a, b, c)))) == 1
      False
      

      【讨论】:

        【解决方案5】:

        如果 l 是长度列表:

        l = [len(a), len(b), len(c)]
        if len(set(l))==1:
            print 'Yay. List lengths are same.'
        

        否则,使用原始列表,可以创建列表列表:

        d=[a,b,c]
        if len(set(len(x) for x in d)) ==1:
            print 'Yay. List lengths are same.'
        

        【讨论】:

          猜你喜欢
          • 2021-12-08
          • 2011-04-14
          • 1970-01-01
          • 2010-11-30
          • 1970-01-01
          • 1970-01-01
          • 2017-07-24
          • 2021-10-16
          • 1970-01-01
          相关资源
          最近更新 更多