简体   繁体   English

如何检查列表列表中的每个列表的长度是否相同

[英]How to check that each list in a list of list is the same length

I have a list and a list of list 我有一个列表和列表清单

A=["grp 1", "grp 2"]
B=[["1","2"],["3","4"],["5","6"]]

how do I check that each list in B is equal to the length of A? 如何检查B中的每个列表是否等于A的长度?

I would like something like 我想要的东西

if len(A) != len(list in B):
     raise ValueError('special error message')

If you want to make sure that every single element of B is not equal to the length of A then you can use: 如果你想确保B每个元素都不等于A的长度,那么你可以使用:

a_len = len(A)
all(len(x) != a_len for x in B)

Alternatively you can use the following if you want to see if any element of B is not the same length as A : 或者,如果要查看B 任何元素是否与A长度不同,您可以使用以下内容:

a_len = len(A)
any(len(x) != a_len for x in B)

So in your case you could use: 所以在你的情况下你可以使用:

a_len = len(A)
if any(len(x) != a_len for x in B):
    raise error

as additional note, if you want to know if every element in the list have the same length regardless of its value, you can use 作为附加说明,如果您想知道列表中的每个元素是否具有相同的长度而不管其值如何,您可以使用

len( set( len(x) for x in my_list ) ) == 1 

with set you eliminate all duplicates so if in the end if its length is more than one then some stuff there have different size 设置你消除所有重复,所以如果最后,如果它的长度超过一个,那么有些东西有不同的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM