John Andrei Gayeta
John Andrei Gayeta

Reputation: 85

How do I stop iterating based on the number of elements on my list?

I have a project wherein I have to get the follow-up elements of elements in on_time.

For example:

j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], [6, 8], [7, 8], 9, 8, 10, 10, 11]
on_time = [4, 5]

The code I have looks like this:

# element in on_time except 1, get follow_finish_act
follow_finish_act = []

for a, d in zip(j_set, s_follow_int):
    if a in on_time and a != 1:
        if len(on_time) > 1:
            follow_finish_act.append(d)
        else:
            follow_finish_act = d

Output I am getting:

follow_finish_act =  [[6, 8], [7, 8]]

Expected Output:

follow_finish_act = [6, 7, 8]

I am having trouble when length of on_time is more than 1. I think the problem is flattening the irregular lists (can be nested and integer) without duplicates. Since, I cannot get my expected output.

Any help/suggestions would be appreciated! Thank you!

Edit: Code I used for trying to flatten output of follow_finish_act

def flatten(lss):
    for item in lss:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

Upvotes: 3

Views: 83

Answers (2)

Suraj
Suraj

Reputation: 2477

You could avoid duplicates by using set instead of list

j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], [6, 8], [7, 8], 9, 8, 10, 10, 11]
on_time = [4, 5]

follow_finish_act = set()

for a, d in zip(j_set, s_follow_int):
    if a in on_time and a != 1:
        if len(on_time) > 1:
            follow_finish_act.update(d)
        else:
            follow_finish_act.update(d)

print(follow_finish_act)
# prints {6,7,8}
print(list(follow_finish_act))
# prints[8,7,6]

Upvotes: 1

quamrana
quamrana

Reputation: 39374

Its difficult to tell what you really want, but looking at the code a lot of it seems superfluous. Try this instead:

j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], 8, 7, 9, 8, 10, 10, 11]
on_time = [6, 5]

follow_finish_act = []
for a, d in zip(j_set, s_follow_int):
    if a in on_time:
        follow_finish_act.append(d)

print(follow_finish_act)

Output:

[7, 9]

If you then get output like: [9], you could do this afterwards:

if len(follow_finish_act) == 1:
    follow_finish_act = follow_finish_act[0]

Upvotes: 1

Related Questions