简体   繁体   中英

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?

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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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