简体   繁体   中英

Python call function with list from loop

I have a function getloantype(account_no) which I would like to call. The account numbers are in a list ['10101-2','10101-2', '10101-3'] and I would like the function to run one by one through all the account numbers and put all the results into another list. However, I cannot seem to get my code to run.

What I do: first, I get the user to input his userID and use it to fetch all the bank accounts that he owns from SQL database:

userid = input("Please enter user id")

conn=create_connection()
def getacct(userid): 
    query = """\
        select Account_Number
        from User_Account
        where UserID = '{}'
        """ .format(userid)

    return (execute_read_query (conn, query))

account_no = getacct(userid)

As such, the account numbers would end up being in a list [account_no]. Next, I will need to use the account number to fetch his Loan ID. From this part comes the first question. Am I supposed to code it as getloanid(account_no) or getloanid(x) whereby x is for x in account_no ?

def getloanid(x): 
    query = """\
        select SUBSTRING(LoanID, 1, 2)
        from Account_Delinquency
        where Account_Number = '{}'
        """ .format(account_no)

    return (execute_read_query (conn, query))

From here, I assume that I should do a nested for loop but the way I coded it, the list remains empty.

loanlist = []

for i in account_no:
    for x in i:
        getloanid(x)
        loanlist.append(i[0])

I have also tried this which would return error:

'NoneType' object is not iterable

mylist = []
loanlist = []

for i in account_no:
    mylist.append(i[0])


for x in mylist:
    a = getloanid(x)
    for i in a:
        loanlist.append(i[0])

How can I code it such that I can call the function getloantype(account_no) with all the account numbers in the list account_no = getacct(userid) and have all the results be appended into a new list [loanlist]?

It is not so clear the structure of your program, and data returned from functions, but if I can undestand, a possible simple solution could be somthing like this:

result_list = [getloantype(account_no) for account_no in account_list]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM