При обработке более одного элемента списка просто необходимо объединить все, кроме наименьшего элемента, с помощью ','
, а затем добавить последний элемент:
wordlist = [['new', 'barn', 'shark', 'hold', 'art', 'only', 'and eyes'],
['subtract', 'and add'],
['girl', 'house', 'best', 'thing', 'easy', 'wrong',
'right', 'again', 'and above'],
['question'],
[]]
def createSentence(wordlist):
if len(wordlist) > 1:
return (f'The {len(wordlist)} sight words for this week are'
f' {", ".join(wordlist[:-1])} {wordlist[-1]}.')
elif len(wordlist) == 1:
return f'The only sight word for this week is {wordlist[0]}.'
elif len(wordlist) == 0:
return 'There are no new sight words for this week!'
for lst in wordlist:
print(createSentence(lst))
Вывод:
The 7 sight words for this week are new, barn, shark, hold, art, only and eyes.
The 2 sight words for this week are subtract and add.
The 9 sight words for this week are girl, house, best, thing, easy, wrong, right, again and above.
The only sight word for this week is question.
There are no new sight words for this week!
Если вы не хотите добавлять 'and '
к своим входным данным, поместите его (включая запятую) в строку формата:
wordlist = [['new', 'barn', 'shark', 'hold', 'art', 'only','eyes'],
['subtract', 'add'],
['girl', 'house', 'best', 'thing', 'easy', 'wrong', 'right', 'again','above'],
['question'],
[]]
def createSentence(wordlist):
if len(wordlist) > 1:
return (f'The {len(wordlist)} sight words for this week are '
f'{", ".join(wordlist[:-1])}, and {wordlist[-1]}.')
elif len(wordlist) == 1:
return f'The only sight word for this week is {wordlist[0]}.'
elif len(wordlist) == 0:
return 'There are no new sight words for this week!'
for lst in wordlist:
print(createSentence(lst))
, чтобы получить тот же результат, что и выше.
Для этого вы используете нарезку списка. Дополнительная информация: Обозначение среза