Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

I have written some code to iterate over a list of lists that returns true or false based on if i at an index in a list is bigger than all other values j at the same index in other lists:

for i in range(len(list)):

    for j in range(0, len(list)):

        if (np.any(list[i]) >= np.all(list[j])):

            count = count + 1

            results.append((count == len(list) - 1))

print (results)

This works fine in finding the right answer. However, the problem is that the function doesn't iterate over the entirety of the list inside the list like I would hope. For example, from a list like this:

list =[[1, 3, 6, 5, 9], [7, 2, 8, 9, 1]]

I would expect an output like this:

results = [False, True, True, False, False, True, False, True, True, False]
However, it is only iterating over the first two indices and stops.
results = [False, True, True, False]
I know this is probably because the length of list is 2, but I don't have a good solution for getting the function to iterate over the entire list inside the list. Any help would be greatly appreciated!

1 Answer

0 votes
by (16.8k points)

Just avoid the usage of the python keywords as variable names for example list. But, if you try calculating the maximum value each column before looping, then you can easily calculate after this:

Code: 

lst = [[1, 3, 6, 5, 9], [7, 2, 8, 9, 1]]

maxes = [max(x) for x in zip(*lst)]

print([r == m for row in lst for r, m in zip(row, maxes)]

Or as a standard for loop:

result = []

for row in lst:

    for r, m in zip(row, maxes):

        result.append(r == m)

Outcome:

[False, True, False, False, True, True, False, True, True, False]

Related questions

+1 vote
2 answers
asked Aug 28, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+3 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...