我正在做一项作业,我们必须按照书中的描述写一个逗号代码
假设您有如下列表值:
spam = ['apples', 'bananas', 'tofu', 'cats']
编写一个函数,该函数将列表值作为参数,并返回一个字符串,其中所有项都由逗号和空格分隔,并在最后一项之前插入和。例如,将以前的垃圾邮件列表传递给函数将返回apples, bananas, tofu, and cats
。但是您的函数应该能够处理传递给它的任何列表值
我们将写下以下细节:
在您的程序中,创建以下四个列表:
animalList1 = ['dog', 'cat', 'bird', 'tiger', 'lion', 'camel']
animalList2 = ['elephant', 'alligator']
animalList3 = ['horse']
animalList4 = []
运行程序时,将每个列表传递给commaCode()
函数,然后打印结果,如示例输出所示
我真的被卡住了,不知道我是否朝着正确的方向前进。这是我目前的代码:
animalList1 = ['dog', 'cat', 'bird', 'tiger', 'lion', 'camel']
animalList2 = ['elephant', 'alligator']
animalList3 = ['horse']
animalList4 = []
spam = [animalList1, animalList2, animalList3, animalList4]
def commacode(list):
spam[-1] = 'and ' + str(spam-[1])
for i in range(len(spam)-1):
spam[i] = str(spam[i]) + ','
stringList = ''
for i in range(len(spam)):
stringList = stringList + str(spam[i])
print(stringList)
print(commacode(spam))
您需要添加异常情况。 使用
.join
使事情变得简单在此处了解有关加入的信息: https://www.geeksforgeeks.org/join-function-python/
在此处了解列表索引和切片: https://towardsdatascience.com/the-basics-of-indexing-and-slicing-python-lists-2d12c90a94cf
我假设您不允许在这里使用
join
。您必须首先处理空列表和单例的特殊情况,然后为最后一个添加具有另一个特殊处理的所有元素下面是一个可能的Python代码:
根据您的数据,它将按预期提供:
(我添加了一个提示显示,使最后一个空行可见)
如果可以使用
join
,else
部分可以是:此代码也可以工作。首先,垃圾邮件列表中有4个列表。所以你需要对它进行迭代。这就是最后两行所做的。每次将列表作为参数传递给
commacode
函数时。根据您的期望,确定列表的长度以检查长度是否为1。如果长度为1,则表示有一项。这样就打印出来了。如果长度为0,则不执行任何操作。如果长度不为零,则迭代列表中的items
,并用逗号连接到字符串。检查每个项目是否为最后一个项目。如果它是最后一项,字符串也将包含和我得到的输出:
相关问题 更多 >
编程相关推荐