好的,所以我正在尝试创建一个函数,它将接收一个项目列表并返回(而不是打印!)该列表中的字符串,在列表中的最后一项之前用逗号分隔。到目前为止,我的脚本如下:
rose1 = Thing("red rose", "flowerbox")
rose2 = Thing("pink rose","garden")
rose3 = Thing("white rose", "vase")
def text_list(things):
"""Takes a sequence of Things and returns a formatted string that describes all of the things.
Things -> string"""
names=[o.name for o in things]
if len(names) == 0:
return 'nothing'
elif len(names) == 2:
names = ' and the '.join(names)
return 'the ' + names
else: #Here's where I need help!
names = ', the '.join(names)
return 'the ' + names在这一点上,函数返回“红玫瑰,粉红色玫瑰,白色玫瑰”,这很好,但我需要最后一个,和“被放置在粉红色玫瑰和白色玫瑰之间,我不能使用打印。”有什么帮助吗?这可能很简单,我完全错过了OTL
发布于 2015-04-19 16:05:41
检查以下内容是否足以满足您的要求。
names=[o.name for o in things[:-1]]
last_name = things[-1].name使用“名称”列表的逻辑获取result_string,并最终将last_name追加到字符串中。
return result_string + ' and the ' + last_name发布于 2022-05-12 15:48:06
你可以用一行来做:
print(', '.join([*lst[:-1], f'and {lst[-1]}']))例如:
a_list = ['a', 'b', 'c']
print(', '.join([*a_list[:-1], f'and {a_list[-1]}']))这就产生了结果
a, b, and c当然,如果列表由单个项目或空列表组成,这将不会给出所需的结果。
https://stackoverflow.com/questions/29732091
复制相似问题