我是 python (2.7.3) 的新手,我正在尝试使用列表。假设我有一个定义为的列表:
my_list = ['name1', 'name2', 'name3']
我可以打印它:
print 'the names in your list are: ' + ', '.join(my_list) + '.'
哪个会打印:
the names in your list are: name1, name2, name3.
我如何打印:
the names in your list are: name1, name2 and name3.
谢谢你。
更新:
我正在尝试下面建议的逻辑,但以下是抛出错误:
my_list = ['name1', 'name2', 'name3']
if len(my_list) > 1:
# keep the last value as is
my_list[-1] = my_list[-1]
# change the second last value to be appended with 'and '
my_list[-2] = my_list[-2] + 'and '
# make all values until the second last value (exclusive) be appended with a comma
my_list[0:-3] = my_list[0:-3] + ', '
print 'The names in your list are:' .join(my_list) + '.'