【问题标题】:How to pass multiple list values as function parameters?如何将多个列表值作为函数参数传递?
【发布时间】:2020-08-03 22:02:15
【问题描述】:

有人能帮我理解如何将多个列表中的值作为函数参数传递吗?我正在尝试使用包含 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

提前致谢!

【问题讨论】:

  • 为什么要在循环中定义函数?你在哪里调用函数?

标签: python list loops python-requests function-invocation


【解决方案1】:

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

为了传递值,使用:

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)

【讨论】:

    【解决方案2】:

    customerId 是列表,y 是该列表中的值。使用

    notes="https://myurl.com/customer?customerId =" + y
    

    【讨论】:

    • @Gabip 对,我问过他们到底在做什么。但我也认为了解导致错误的原因很有用。
    • 同意,我后来看到你的评论,所以我删除了我的评论......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    相关资源
    最近更新 更多