更好的方法来检查列表中的所有列表是否都是相同的长度?

nls*_*bch 6 python algorithm python-3.x

目前正在运行:

l1 = [i for i in range(0,10)]
l2 = [i for i in range(0,10)]
l3 = [i for i in range(0,10)]
lists = [l1, l2, l3]
length = len(lists[0])
for l in lists:
    if length != len(l):
        raise ValueErrorr('not all lists have same length!')
Run Code Online (Sandbox Code Playgroud)

有没有比for循环测试更漂亮的方法?是否有更快/更好的方式O(n)

Kas*_*mvd 8

您可以使用集合理解来保留唯一长度,然后检查集合中是否只有一个项目:

if len({len(i) for i in lists}) == 1:
    # do stuff
Run Code Online (Sandbox Code Playgroud)

或者作为更有效的方式,您可以在anyor 中使用生成器表达式all

def check_size_eq(lst):
    # returns true if there's any list with unequal length to the first one
    return not any(len(lst[0])!= len(i) for i in lst)
    # or you could do:
    # return all(len(lst[0])== len(i) for i in lst)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> a = {1}
>>> 
>>> a.pop() and not a
True
>>> a = {1,3}
>>> a.pop() and not a
False
Run Code Online (Sandbox Code Playgroud)

  • 我的意思是它不会在第一个 `len()` 不同时退出,对吗?因此,最坏和最好的情况是 O(n)? (2认同)

tim*_*geb 8

我用生成器表达式做到了all:

>>> it = iter(lists)
>>> the_len = len(next(it))
>>> if not all(len(l) == the_len for l in it):
...     raise ValueError('not all lists have same length!')
Run Code Online (Sandbox Code Playgroud)

这避免了两次检查第一个列表的长度,并且不构建一次性列表/设置数据结构.

all也懒惰地评估,这意味着False一旦产生了第一个长度不同的列表,它就会停止并返回.


Mat*_*hew 6

您可以使用map函数来获取列表的长度(在python3中,这将是一个迭代器)

lengths = map(len,lists)
Run Code Online (Sandbox Code Playgroud)

然后您可以对其应用 set 函数,将其转换为一组唯一值。如果只有一个值,则它们的长度相同。

if len(set(map(len,lists)))==1:
    print("All are the same length")
else:
    print("They are not the same length!")
Run Code Online (Sandbox Code Playgroud)