如何在另一个函数中使用返回的列表?

时间:2019-10-03 16:54:03

标签: python python-3.x

如果我有一个函数并且它返回了三个列表,那么如何引用或调用返回的列表之一?

例如,我正在使用该API,并且我将返回三个列表ids, names, emails。有没有办法只引用ID?我尝试了users_info(ids),但是没有用。它只是给NameError指出名称“ ids”未定义。

def users_info():

    url = 'https://slack.com/api/users.info'
    headers = {'Accept': 'application/x-www-form-urlencoded'}

    users = channels_info() # the user IDs from channels.info
    ids = []
    names = []
    emails = []
    # loops for every user
    for user in users:
        payload = {
            'token': API_KEY,
            'user': user
        }
        r = requests.get(url, headers=headers, params=payload)
        id = r.json()['user']['id']
        email = r.json()['user']['profile'].get('email') 
        name = r.json()['user']['real_name']

        if r.status_code == 200:
            # This is to ignore the users that don't have an email field
            if email is not None:
                ids.append(id)
                emails.append(email)
                names.append(name)
        else:
            return None
    # result returns a list of ids, names, and emails of the users
    return ids, names, emails

我正在尝试将users_info()返回的ID用作另一个API的有效载荷的一部分,但我仍然需要名称和电子邮件,因此这些名称和电子邮件也会与ID一起返回。

2 个答案:

答案 0 :(得分:3)

这是一种方法:

ids, names, emails = user_info()
# Use ids here

答案 1 :(得分:2)

执行此操作

ids, names, emails = user_info()     

这是一个关于多次收益的演示(示例):

 def func():
 ...     return ['a','b'], ['c','d'], ['e','f']
 ...
 >>> x,y,z = func()
 >>> x
 ['a', 'b']
 >>> y
 ['c', 'd']
 >>> z
 ['e', 'f']