Skip to main content
 首页 » 编程设计

python之定义一个函数,该函数接受项目列表并返回以逗号分隔的项目名称列表

2024年12月31日9bluestorm

抱歉,我是 Python 的新手,一直在使用这个函数。

item_pencil = { 
    "id": "pencil", 
 
    "name": "a HB Pencil", 
 
    "description": 
    "Normal pencil" 
} 
 
item_pen = { 
    "id": "pen", 
 
    "name": "a Ballpoint Pen", 
 
    "description": 
    "Standard ballpoint pen" 
} 

我编写了这个函数,但它返回了关于项目的所有信息

def list_of_items(items): 
    n = ",".join(map(str, items)) 
    #n = ",".join([str(name) for name in items]) 
    return n 
 
print(list_of_items([item_pen, item_pencil])) 

我得到的结果

{'id': 'pen', 'name': 'a Ballpoint Pen', 'description': 'Standard ballpoint pen.'},  
{'id': 'pencil', 'name': 'a HB Pencil', 'description': 'Normal Pencil'} 

但是我想要的输出是这样的

'a Ballpoint Pen, a HB Pencil' 

如果我遗漏了一些明显的东西,我很抱歉。提前致谢

请您参考如下方法:

你快接近了。您需要遍历列表并获取 'name' 键的值:

def list_of_items(items): 
    n = ", ".join([item['name'] for item in items]) 
    return n 

您可以同时使用列表理解或生成器:

', '.join([item['name']) for item in items])  # list comprehension 
', '.join(item['name'] for item in items)     # generator expression 

但是列表推导式既更快又更节省内存[ source ].