-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.

%sですstring 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 に答える