简体   繁体   中英

Python checking if all item in nested list are the same

Simple question how would you find that all the elements in a nested list are equal to 0 or specific value my code goes like this

a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break

is there any other better way to do this? without importing any libraries

You can iterate through all sublists of a and check if the count of 0s is equal to the length of the sublist, meaning it contains only 0s, and then check if all of the resulting values are True :

a = [[0,0,0],[0,0,0]]
def checkall(a):
    return all(el.count(0) == len(el) for el in a)

This results in

>>> checkall(a)
True

The following expression returns True if all elements are 0 (or False), else return False

not any(any(x) for x in a)

You could use list comprehension:

b = [True if d==0 else False for i in a for d in i]
all(b)

The first line creates a list of boolean values (True if the element is zero, False otherwise). Then the second line checks if all the list consists of True values.

You could try this:

def checkNested(ls,n):
    total = 0
    for i in ls:
        total += i.count(n)
    return total

Where ln is the list (must have nested lists) and n is the number you are checking. It returns the total n's found in your nested lists. checkNested([[0,0,0],[0,0,0]]) returns 6.

A simple function can do this:

def is_sublists_equal(master_list:list, element)->bool:
    '''
    Checks if all sublists are equal to given item
    '''
    i=0
    if master_list[0][0]!=element:
        return False
    while master_list[0]==master_list[i]:
        i+=1
        if i>(len(master_list)-1):
            return True
    else:
        return False

Example:

is_sublists_equal([['a','a','a'], ['a','a','a'], ['a','a','a']], 'a') #returns True
is_sublists_equal([['a','a','a'], ['a','b','a'], ['a','a','a']], 'a') #returns False
is_sublists_equal([['a','a','a'], ['a','a','a'], ['a','a','a']], 'b') #returns False

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