简体   繁体   中英

Iterating over lists within a list

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!

Try to avoid using Python keywords as variable names (eg: list ). But if you calculate the maximum value per column before looping, you can then more easily calculate what you after like 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)

Results:

[False, True, False, False, True, True, False, True, True, 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