简体   繁体   中英

Check if a column in a 2D list contains the same values

For example, a = [[1,2,3],[1,2,3],[1,2,3]] has 3 columns with the same values

I'm trying to check How can I do this without using numpy arrays? I essentially need help iterating over columns instead of rows.

You could iterate over the columns with a loop, and for each column check the all the row values are equal to the first rows:

def numUniformColumns(mat):
    cnt = 0
    for j in range(0, len(mat[0])):
        first = mat[0][j]
        uniform = True
        for i in range(1, len(mat)):
            if first != mat[i][j]:
                uniform = False
                break;

        if uniform:
            cnt += 1

    return cnt

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