将列表中的任何列表分配给字符串脚本。

2024-05-27 11:17:23 发布

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

我正在做第4章中的一个项目,用Python自动化那些无聊的东西。以下是项目提示:

"For practice, write programs to do the following tasks. Comma Code Say you have a list value like this: spam = [' apples', 'bananas', 'tofu', 'cats'] Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it."

我编写了一个脚本,它在最后一项之前创建一个带有逗号和“and”的列表:但是我不知道如何在传递给它的任何列表值的情况下使脚本工作。我尝试过使用input函数来调用list,但这不起作用(或者我无法工作),因为input函数只接收字符串而不接收列表名称?在

以下是我所得到的最远距离:

def listToString(list):
    if list[-1]:
        list.append('and '+str(list[-1]))
        list.remove(list[-2])
    for i in range(len(list)):
        print(''+list[i]+', ')

spam = ['apples', 'bananas', 'tofu', 'cats']
listToString(spam)

至于使用input()函数,下面是我尝试过的没有用的代码。我在shell编辑器中输入垃圾邮件列表并运行以下命令:

^{pr2}$

Tags: andtheto函数列表inputvaluewith
3条回答

我认为最简单的方法是用“and…”替换最后一个元素,然后用“,”连接所有元素

def merge(list):
  return ', '.join(list[:-1] + ['and '+list[-1]])

我相信“但是您的函数应该能够处理传递给它的任何列表值。”这意味着您不应该在函数中硬编码示例列表(['apples'、'bananas'、'tofu'、'cats'])。在

因此,函数的最简单形式是:

def listToString(list):
    return "{} and {}".format(", ".join(list[:-1]]), list[-1])

但是,如果要处理字符串以外的其他类型以及少于2个元素,则函数将变为:

^{pr2}$

下面是一个简单的解决方案,它只使用Chapter 4中已经包含的语法:

def toString(arr):
    s = ''
    for i in range(len(arr)):
        if i > 0:
            if i == len(arr) - 1:
                # last one
                s = s + ' and '
            else:
                # second, third, ...
                s = s + ', '
        s = s + arr[i];
    return s

它适用于具有任意数量元素的数组。在

相关问题 更多 >

    热门问题