Добрый вечер, утро, ночь или день форумчане!
Решал такую вот задачу.
Exercise 113: Formatting a List
(Solved—43 Lines)
When writing out a list of items in English, one normally separates the items with
commas. In addition, theword “and” is normally included before the last item, unless
the list only contains one item. Consider the following four lists:
apples
apples and oranges
apples, oranges and bananas
apples, oranges, bananas and lemons
Write a function that takes a list of strings as its only parameter. Your function
should return a string that contains all of the items in the list formatted in the manner
described previously as its only result. While the examples shown previously only
include lists containing four elements or less, your function should behave correctly
for lists of any length. Include a main program that reads several items from the user,
formats them by calling your function, and then displays the result returned by the
function.
Решение вот такое
def itemlist(a):
—a = a.split(' ‘)
—print(len(a))
—x = ’'
—if len(a) == 1:
——-x += a
—elif len(a) == 2:
——-x += a + ‘ and ’ + a
—elif len(a) == 3:
——-x += a + ‘, ’ + a + ‘ and ’ + a
—elif len(a) > 3:
——-for i in range(len(a)-2):
———–x += a + ‘, ’
——-x += a + ‘ and ’ + a
—return x
a = input('Введите через пробел список итемов \n')
print(itemlist(a))
Подскажите пожалуйста как решить её с использованием возможностей .format, если это вообще возможно и будет более лаконично (http://pythonworld.ru/osnovy/formatirovanie-strok-metod-format.html) или более оптимизированными вариантами.
Спасибо большое!