我想知道如何使用 assert 来保证列表列表中的所有元素都具有相同的长度

I would like to know how could I use assert to guarantee that all my elements of a list of lists have the same length

我想确保列表列表中的所有元素都具有相同的长度。

我试过了:

assert len((map(len,motifs))) == len(motifs[0])

然后:

assert all(len(m[i]) == len(m[0]) for i, m in enumerate(motifs))

你有什么干净快捷的建议吗?

l = [...]
length = <Specified length or len(l[0])>
assert all(len(x) == length for x in l)

您可以为 length 参数使用任何预定义值,或者您可以简单地使用列表列表中任何项目的长度(使用 len)。

assert all( [len(item) == len(motifs[0][0]) for sublist in motifs for item in sublist] )