我要把权利拿出来:
需要我的输出看起来像这样:
本周的7个视觉词汇是新的,谷仓,鲨鱼,货舱,艺术,只有,和眼睛。 本周的两个单词是减法、和加法。 本周的9个单词是:女孩、房子、最好的、东西、简单、错误、正确、再次、和上面的。 本周唯一的词汇是疑问。 本周没有新的视觉词汇
但我想知道在报税表中最后一个字之前的“和”。这是否恰当
这是代码:
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:
wordlist[-1] = "and " + wordlist[-1]
return f'The {len(wordlist)} sight words for this week are {", ".join(wordlist)}.'
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))
听起来像是要将
"and "
添加到数组/列表中最后一个元素的开头,但前提是您有多个单词Python有一种非常简单的方法来获取数组/列表的最后一个元素
在前面加上“和”:
最终的代码应该是这样的
您可以将第一个
n-1
元素与,
连接起来,并在末尾添加and nth element
:这样您就不需要在输入列表的最后一个单词之前手动添加
and
case handling than 1 list元素只需将除最小元素外的所有元素与
','
连接,然后添加最后一个元素:输出:
如果不想将
'and '
添加到输入中,请将其(包括逗号)放入格式字符串中:以获得与上述完全相同的输出
您可以使用列表切片。更多信息:Understanding slice notation
相关问题 更多 >
编程相关推荐