简体   繁体   English

Python 使用循环列表调用 function

[英]Python call function with list from loop

I have a function getloantype(account_no) which I would like to call.我有一个 function getloantype(account_no)我想打电话。 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.帐号在列表['10101-2','10101-2', '10101-3'] ,我希望 function 逐个运行所有帐号并将所有结果放入另一个列表. 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:我做什么:首先,我让用户输入他的用户 ID,并使用它从 SQL 数据库中获取他拥有的所有银行账户:

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].因此,帐号最终会出现在列表 [account_no] 中。 Next, I will need to use the account number to fetch his Loan ID.接下来,我需要使用帐号来获取他的贷款 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 ?我是否应该将其编码为getloanid(account_no)getloanid(x)其中 x 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.从这里开始,我假设我应该做一个嵌套的 for 循环,但是按照我的编码方式,列表仍然是空的。

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 'NoneType' object 不可迭代

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]?如何对其进行编码,以便我可以使用列表account_no = getacct(userid)中的所有帐号调用 function getloantype(account_no)并将所有结果附加到新列表 [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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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