isb
isb

Reputation: 53

python: getting the output from multiple for loops outside of the for loop

I have a nested for loops as you can see below:

cv_list_dic = cv_list()
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id = (cv_name, max_id)
            print(qq_cv_id)

the output is a list of tuples (there is much more tuples, its just example):

('cv1', 152)
('cv2', 35)

My issue that I need those tuples outside of those for loops. I have tried to create an empty list and append to it but it's appending only the last item.

Upvotes: 0

Views: 65

Answers (2)

xiº
xiº

Reputation: 4687

I have tried to create an empty list and append to it

That is right direction, so you just need to actually code it :)

cv_list_dic = cv_list()
results = [] # here is your list with results
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id = (cv_name, max_id)
            print(qq_cv_id)
            results.append(print(qq_cv_id))

Upvotes: 1

omri_saadon
omri_saadon

Reputation: 10661

This should work, define cv_list_dic as an empty list (before the loop starts) and append each iteration the result into this list.

cv_list_dic = cv_list()
qq_cv_id = []
for cv in cv_list_dic['results']:
    cv_name = cv['name']
    if qq_cv(cv_name):
            cv_versions = (cv['versions'])
            cv_id_list = []
            for cv_ids in cv_versions:
                    ver_id = (cv_ids['id'])
                    cv_id_list.append(ver_id)
            max_id = (max(cv_id_list))
            qq_cv_id.append((cv_name, max_id))
            print(qq_cv_id)

Upvotes: 0

Related Questions