首页 > 解决方案 > 如何将多个列表值作为函数参数传递?

问题描述

有人可以帮助我理解如何将多个列表中的值作为函数参数传递吗?我正在尝试使用包含 customerId 的 url 更新每个 myemailId 的电子邮件。

到目前为止我的代码:

emailId = [732853380,7331635674]
customerId = ['cust-12345-mer','cust-6789-mer']

for x, y in zip(emailId, customerId):
    def update_email(emailId, token, user, notes="https://myurl.com/customer?customerId =" + customerId):
        headers = {     'accept': 'application/json',
                    'Content-Type': 'application/json',
                    'token': token,
                    'user': user}
        endpoint = 'email/'
        body = {'emailId': emailId, 'user': user, 'notes': notes}
        requests.put(url = host + endpoint, headers = headers, json=body)
        return True

但收到与以 ... 开头的行相对应的此错误def update_email

TypeError: must be str, not list

提前致谢!

标签: pythonlistloopspython-requestsfunction-invocation

解决方案


首先,您不应该为每次循环迭代定义函数,而是在执行循环之前定义一次。

为了传递值,请使用:

emailId = [732853380, 7331635674]
customerId = ['cust-12345-mer', 'cust-6789-mer']


def update_email(emailId, token, user, customerId):
    notes = "https://myurl.com/customer?customerId =" + customerId
    headers = {'accept': 'application/json',
               'Content-Type': 'application/json',
               'token': token,
               'user': user}
    endpoint = 'email/'
    body = {'emailId': emailId, 'user': user, 'notes': notes}
    requests.put(url=host + endpoint, headers=headers, json=body)
    return True


for x, y in zip(emailId, customerId):
    update_email(x, token, user, y)


推荐阅读