首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从函数返回集合

问如何从函数返回集合
EN

Stack Overflow用户
提问于 2021-04-28 00:28:56
回答 1查看 50关注 0票数 0

我使用集合的namedtuple从函数中返回一个元组列表,如下所示:

代码语言:javascript
复制
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

如果我运行

代码语言:javascript
复制
callGetItems = getItems(list_of_things)  # assume list_of_things is a dictionary
print(callGetItems)

它将只打印返回值的第一个索引,正如您所看到的,我实际上希望打印整个字典,并显示它们各自的id和标题(假设字典中至少有3个不同的键值对)。

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

为了消除混淆,假设这是字典list_of_things:

代码语言:javascript
复制
list_of_things = [
    {"id" : 1,
     "title" : "waterbottle",
     "description" : "a liquid container"},
    {"id": 2,
     "title": "lunchbox",
     "description": "a food container"}
]
# etc... 
EN

回答 1

Stack Overflow用户

发布于 2021-04-28 00:55:04

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

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67287050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档