0

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

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

1 Comment

the original form of sub_change is sub,150,aaa sub,151,bbb sub,152,ccc sub,153,dddd -------------------------------------- sub_code_stop.csv form is sub,150,aaa sub,151,bbb sub,152,ccc sub,153,dddd . . . I want to change row[1] in sub_change to row[2] and allocate it to 2D dictionary like this (first = {'aaa':{'bbb':[]}, 'ccc':{'ddd':[]}}) but the second sub_code_stop('150') return 0
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.