【问题标题】:access just one return value from function with multiple return values从具有多个返回值的函数中仅访问一个返回值
【发布时间】:2018-07-06 22:52:42
【问题描述】:

我无法弄清楚如何访问从要返回多个值的函数返回的值。我有一个字典对象,其中包含这样的值的元组。

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)

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

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 需要的格式。

【问题讨论】:

  • 不清楚你想要什么,但也许my_gen = ([..., *pick_card_combo(), ...] for i in range(accs_gend)])? (无论如何,在 Python 3 中。)
  • @chepner ...我认为他的信息仍然嵌套在它自己的子列表中,但这也是我在思考的途径a,b = pick_card_combo();my_gen = ([first_name(), last_name(), country,]+ [a,] + b)
  • 你能给我们一个更完整的例子吗?你的pick_card_combo 函数只是一个NameError,我不知道你的my_gen 应该做什么。如果你不能用英语解释你想让它做什么,你能把它写成一个明确的、冗长的列表语句吗?
  • 我想用 key(rand_dict) 和 info 元组中的每个单独元素填充 my_gen。这 4 个“属​​性”将在 my_gen 中生成的列表中有自己的单独元素。如果我将 pick_card_combo() 放入 my_gen 中包含的列表中,那么它会将类似这样的内容添加到列表中,('12345678121365489', ('11', '2022', '666'))。我宁愿将“12345678121365489”、“11”、“2022”、“666”作为单独的元素附加到列表中。
  • @JoranBeasley 实际上。我编辑我刚才说的。这不是我所需要的,但我认为这是一个开始。谢谢

标签: python generator return-value xlsxwriter


【解决方案1】:

分解更多

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2014-01-03
    • 2020-05-04
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 2022-04-29
    相关资源
    最近更新 更多