如何从函数返回集合

hwazgwia  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(499)

我正在使用collection的namedtuple从函数中返回元组列表,如下所示:

  1. def getItems(things_list) -> list:
  2. for i, j in enumerate(things_list):
  3. [*things_id] = things_list[i].id
  4. [*things_title] = things_list[i].title
  5. things_structure = namedtuple('things', ['id', 'title'])
  6. [*things_list] = [
  7. things_structure(things_id, things_title)
  8. ]
  9. return things_list

如果我跑了

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

它只打印返回值的第一个索引,正如您所看到的,我实际上希望整个字典都打印出它们各自的id和title(假设字典中至少有3个不同的键值对)
p、 如果我在函数内打印,它会按预期打印存储在[*things\u list]变量中的所有元素,但对于迭代返回值(即在函数外)不能这样说。请帮忙。
要去除泡沫,假设这是字典中的物品列表:

  1. list_of_things = [
  2. {"id" : 1,
  3. "title" : "waterbottle",
  4. "description" : "a liquid container"},
  5. {"id": 2,
  6. "title": "lunchbox",
  7. "description": "a food container"}
  8. ]
  9. # etc...
jmo0nnb3

jmo0nnb31#

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

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

相关问题