Python代码添加和

2024-09-30 06:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一项作业,我们必须按照书中的描述写一个逗号代码

假设您有如下列表值:

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

Tags: 函数代码列表spam逗号catsstrtofu
3条回答
def foo(mylist):
    if len(mylist) == 0:
        return ""
    elif len(mylist) == 1:
        return mylist[0]
    else:
        return ", ".join(mylist[:-1]) + " and " + mylist[-1]

您需要添加异常情况。 使用.join使事情变得简单

在此处了解有关加入的信息: https://www.geeksforgeeks.org/join-function-python/

在此处了解列表索引和切片: https://towardsdatascience.com/the-basics-of-indexing-and-slicing-python-lists-2d12c90a94cf

我假设您不允许在这里使用join。您必须首先处理空列表和单例的特殊情况,然后为最后一个添加具有另一个特殊处理的所有元素

下面是一个可能的Python代码:

def commacode(lst):
    # an empty list gives a blank string
    if len(lst) == 0:
        cr =  ''
    # a single element list returns its element
    elif len(lst) == 1:
        cr = lst[0]
    # else all elements are joined with  ' ,' except last with ', and'
    else:
        cr = lst[0]
        # list has at least 2 elements so list[1:-1] is defined
        # (it is at least empty for just 2 elements)
        for elt in lst[1:-1]:
            cr += ', ' + elt
        # special processing for the last element
        cr += ', and ' + lst[-1]
    return cr

for lst in spam:
    print(commacode(lst))

根据您的数据,它将按预期提供:

dog, cat, bird, tiger, lion, and camel
elephant, and alligator
horse

>>>

(我添加了一个提示显示,使最后一个空行可见)


如果可以使用joinelse部分可以是:

    else:
        # list has at least 2 elements so list[1:-1] is defined
        # (it is at least empty for just 2 elements)
        cr = ', '.join(lst[:-1]
        # special processing for the last element
        cr += ', and ' + lst[-1]

此代码也可以工作。首先,垃圾邮件列表中有4个列表。所以你需要对它进行迭代。这就是最后两行所做的。每次将列表作为参数传递给commacode函数时。根据您的期望,确定列表的长度以检查长度是否为1。如果长度为1,则表示有一项。这样就打印出来了。如果长度为0,则不执行任何操作。如果长度不为零,则迭代列表中的items,并用逗号连接到字符串。检查每个项目是否为最后一个项目。如果它是最后一项,字符串也将包含和

from varname import nameof

animalList1 = ['dog', 'cat', 'bird', 'tiger', 'lion', 'camel']
animalList2 = ['elephant', 'alligator']
animalList3 = ['horse']
animalList4 = []
spam = [animalList1, animalList2, animalList3, animalList4]
name_of_list = [nameof(animalList1), nameof(animalList2), nameof(animalList3), nameof(animalList4)]

string = ""
counter = 0

def commacode(list, list_name):
    global string

    length = len(list)
    if length == 1:
        string = list[0]
    elif length != 0:
        for item in list:
            if list.index(item) == length-1:
                string = string + "and " + str(item) 
            else:
                string = string + str(item) + ", "
    else:
        string = "-"
    print(f"{list_name}: {string}")
    string = ""

for list in spam:
    commacode(list, name_of_list[counter])
    counter += 1

我得到的输出:

animalList1: dog, cat, bird, tiger, lion, and camel
animalList2: elephant, and alligator
animalList3: horse
animalList4: -

相关问题 更多 >

    热门问题