从具有多个返回值的函数中仅访问一个返回值

时间:2018-07-06 22:52:43

标签: python generator return-value xlsxwriter

我在弄清楚如何访问从我要返回多个值的函数返回的值时遇到了麻烦。我有一个包含这样的值的元组的字典对象。

import random

payments = {'12345678121365489': ('11', '2022', '666'),
            '5136982546823120': ('03', '2021', '523')}

def pick_card_combo():
    rand_dict, info = random.choice(list(practice_dict.items()))
    return(rand_dict, info)

当然,我可以为“ info”元组建立索引并挑选出某些元素,但是我想知道如何在此函数中为生成器表达式获取每个单独的索引。

def create_accounts(accs_gend):
    my_gen = ([first_name(), last_name(), country, pick_card_combo()
               <rand_dict>, <info[0]>, <info[1]>, <info[2]>] for i in range(accs_gend))
    account = tuple(my_gen)
    print(account)

我在该词典中有不同的项目,因此我希望将各种项目与我生成的不同元组一起使用,而不仅仅是一个项目。为什么这里每次访问一个新元素时都要调用此函数?

我也喜欢将生成器对象也保留在元组中,因为这是xlsxwriter要求的格式。

1 个答案:

答案 0 :(得分:0)

进一步分解

def create_account():
    """ create one single account """
    rand_dict, info = pick_card_combo()
    return ([first_name(), last_name(), country,]+ [rand_dict,] + info )

def create_accounts(accs_gend):
    """ Create some number of random accounts """
    for i in range(accs_gend):
        yield create_account() # by using yield this is a "generator" 

five_random_accounts = tuple(create_accounts(5)) # calling tuple will evaluate the generator and create a tuple of all the elements
相关问题