如何从函数返回集合

问题描述

我正在使用集合的命名元组函数中返回元组列表,如下所示:

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... 

解决方法

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

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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...