【问题标题】:How to return collection from a function如何从函数返回集合
【发布时间】:2021-04-27 16:28:56
【问题描述】:

我正在使用集合的 namedtuple 从函数中返回一个元组列表:

def getItems(things_list) -> list:
    for i, j in enumerate(things_list):
        [*things_id] = things_list[i].id
        [*things_title] = things_list[i].title
        things_structure = namedtuple('things', ['id', 'title'])
        [*things_list] = [
            things_structure(things_id, things_title)
        ]
    return things_list

如果我跑

callGetItems = getItems(list_of_things)  # assume list_of_things is a dictionary
print(callGetItems)

它只会打印返回值的第一个索引,如您所见,我实际上希望整个字典都打印出它们各自的 id 和标题。(假设至少有 3 个不同的键值对字典)

附:如果我在函数内打印,它会按预期打印存储在 [*things_list] 变量中的所有元素,但对于迭代返回值(即在函数外部)则不能这样说。请帮忙。

要对事物进行去混淆假设这是字典 list_of_things:

list_of_things = [
    {"id" : 1,
     "title" : "waterbottle",
     "description" : "a liquid container"},
    {"id": 2,
     "title": "lunchbox",
     "description": "a food container"}
]
# etc... 

【问题讨论】:

  • 你的事物列表是一个列表字典。我认为你的意思是翻转你的 { 和 [ 符号。并创建一个字典列表。对吗??
  • @BradDay 是的,就像那样。抱歉,我可能在解释中混淆了一些东西。

标签: python function collections return namedtuple


【解决方案1】:

这就是你想要的吗?从原始字典列表创建命名元组列表?

from collections import namedtuple
list_of_things = [
    {"id": 1, "title": "waterbottle", "description": "a liquid container"},
    {"id": 2, "title": "lunchbox", "description": "a food container"},
]
def getItems(things_list) -> list:
    things_structure = namedtuple("things", ["id", "title"])
    return [things_structure(k["id"], k["title"]) for k in things_list]
new_things = getItems(list_of_things)
print(new_things)

【讨论】:

  • 感谢这项工作!但我刚刚意识到我可以使用 python 的 append() 方法将元组附加到变量列表中,然后在最后返回。但是,如果我弄错了,您能否解释一下该返回行在您的示例中是如何工作的? k["id"], k["title"] - k 是否对字典中的每个键进行索引并与 ["id"] 等进行混合匹配?
  • 是的,我们正在使用列表理解。我们正在迭代 thing_list 的元素,这是一个字典列表,然后每个 k 是一个字典,我们使用键 idtitle 来索引 k 并放入命名的元组中。我可能应该使用与 k 不同的变量名,因为这可能会让人感到困惑,使它看起来好像意味着键
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2012-12-18
相关资源
最近更新 更多