【问题标题】:Python call function with list from loop带有循环列表的Python调用函数
【发布时间】:2021-04-19 11:59:17
【问题描述】:

我有一个函数getloantype(account_no) 我想调用它。帐号在列表['10101-2','10101-2', '10101-3'] 中,我希望该函数逐个运行所有帐号并将所有结果放入另一个列表中。但是,我似乎无法让我的代码运行。

我做什么:首先,我让用户输入他的用户 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)

因此,帐号最终会出现在列表 [account_no] 中。接下来,我需要使用帐号来获取他的贷款 ID。第一个问题由此而来。我应该将其编码为 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))

从这里开始,我假设我应该做一个嵌套的 for 循环,但按照我的编码方式,列表仍然是空的。

loanlist = []

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

我也试过这个会返回错误:

'NoneType' 对象不可迭代

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])

如何编码,以便我可以使用列表account_no = getacct(userid) 中的所有帐号调用函数getloantype(account_no),并将所有结果附加到新列表[loanlist] 中?

【问题讨论】:

  • "'NoneType' 对象不可迭代" - full 回溯是什么?你确定getloanid(x) 不返回None
  • 强制提醒不要使用字符串格式来构造 SQL 查询。

标签: python list loops for-loop nested-loops


【解决方案1】:

你的程序结构和函数返回的数据不是很清楚,但如果我能理解,一个可能的简单解决方案可能是这样的:

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

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    相关资源
    最近更新 更多