-1

我是 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) + '.'
4

2 回答 2

2

试试这个:

my_list = ['name1', 'name2', 'name3']
print 'The names in your list are: %s, %s and %s.' % (my_list[0], my_list[1], my_list[2])

结果是:

The names in your list are: name1, name2, and name3.

%sstring formatting。_


如果长度my_list未知:

my_list = ['name1', 'name2', 'name3']
if len(my_list) > 1: # If it was one, then the print statement would come out odd
    my_list[-1] = 'and ' + my_list[-1]
print 'The names in your list are:', ', '.join(my_list[:-1]), my_list[-1] + '.'
于 2013-03-17T02:21:48.593 回答
0

我的两分钱:

def comma_and(a_list):
    return ' and '.join([', '.join(a_list[:-1]), a_list[-1]] if len(a_list) > 1 else a_list)

似乎在所有情况下都有效:

>>> comma_and(["11", "22", "33", "44"])
'11, 22, 33 and 44'
>>> comma_and(["11", "22", "33"])
'11, 22 and 33'
>>> comma_and(["11", "22"])
'11 and 22'
>>> comma_and(["11"])
'11'
>>> comma_and([])
''
于 2014-06-18T12:25:19.313 回答