Stellera
Stellera

Reputation: 77

Python multiple loops

A = [[[1,2,3],[4]],[[1,4],[2,3]]]

Here I want to find lists in A which sum of all sublists in list not grater than 5.

Which the result should be [[1,4],[2,3]]

I tried a long time to solve this problem in python. But I still can't figure out the right solution, which I stuck at loop out multiple loops. My code as follows, but its obviously wrong, how to correct it?

A = [[[1,2,3],[4]],[[1,4],[2,3]]]
z = []
for l in A:
    for list in l:
        sum = 0
        while sum < 5:
            for i in list:
                sum+=i
        else:
            break
    else:
        z.append(l)
print z

Asking for help~

Upvotes: 0

Views: 99

Answers (4)

JkShaw
JkShaw

Reputation: 1947

The one with all()

[t for item in A for t in item if all(sum(t)<=5 for t in item)]

Upvotes: 0

Kruup&#246;s
Kruup&#246;s

Reputation: 5484

Simplification of @KindStranger method in a one-liner:

>> [sub for x in A for sub in x if max(sum(sub) for sub in x) <= 5]
[[1, 4], [2, 3]]

Upvotes: 2

Gaurav Ojha
Gaurav Ojha

Reputation: 1187

A simple solution which you can think of would be like this -

A = [[[1,2,3],[4]],[[1,4],[2,3]]]

r = []   # this will be our result

for list in A:  # Iterate through each item in A
    f = True    # This is a flag we set for a favorable sublist
    for item in list:  # Here we iterate through each list in the sublist
        if sum(item) > 5:  # If the sum is greater than 5 in any of them, set flag to false
            f = False
    if f:       # If the flag is set, it means this is a favorable sublist
        r.append(list)

print r

But I'm assuming the nesting level would be the same. http://ideone.com/hhr9uq

Upvotes: 0

Kind Stranger
Kind Stranger

Reputation: 1761

This should work for your problem:

>>> for alist in A:
...     if max(sum(sublist) for sublist in alist) <= 5:
...         print(alist)
...
[[1, 4], [2, 3]]

Upvotes: 0

Related Questions