我使用集合的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... 发布于 2021-04-28 00:55:04
这就是你想要的吗?从原始字典列表创建命名元组列表?
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)https://stackoverflow.com/questions/67287050
复制相似问题