Se_ung
Se_ung

Reputation: 11

python, I want to use function in for loop

I want to use sub_code_stop in for loop (in list)

sub_change = [[0, '150', 'aaa'], [0, '151', 'ccc'],
              [0, '152', 'bbb'], [0, '152', 'ddd']]


def sub_code_stop(a):
    for cc in sub_change:
        if a == cc[1]:
            return cc[2]
        else:
            return 0


lis = [['150', '151'], ['152', '153']]
for i in lis:
    print(sub_code_stop(i[0]))

Return is

aaa
0

I want

aaa
bbb

Upvotes: 0

Views: 113

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Change the function to:

def sub_code_stop(a):
    for cc in sub_change:
        if a == cc[1]:
            return cc[2]

    return 0

Your previous code was comparing with only the first element of sub_change.


If the second element of each sublist in sub_change were unique, you could do:

sub_change = [[0, '150', 'aaa'], [0, '151', 'ccc'],
              [0, '152', 'bbb'], [0, '153', 'ddd']]
sub_dict = {b:c for _,b,c in sub_change}
lis = [['150', '151'], ['152', '153']]
for i in lis:
    print(sub_dict.get(i[0],0))

Upvotes: 4

Matthias
Matthias

Reputation: 13222

In your current code if the first element does not match, you leave the function with the return in the else part. You'll have to continue looping to test the next elements.

If you find something you return the appropriate value. If you don't find anything then you have to deal with that after the loop is finished.

def sub_code_stop(a):
    for cc in sub_change:
        if a == cc[1]:
            return cc[2]
    return 0

Upvotes: 2

Related Questions