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

标签 python list python-3.x

我正在处理《使用 Python 自动化无聊的东西》第 4 章中的一个项目。这是项目的提示:

"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”的列表:但我无法弄清楚如何让脚本处理传递给它的任何列表值。我试过使用输入函数调用列表,但这不起作用(或者我无法开始工作),因为输入函数只接收字符串而不接收列表名称?

这是我最远的距离:

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 编辑器中输入垃圾邮件列表并运行:

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]+', ')

list = input("What list do you want to use?")
listToString(list)

最佳答案

这是一个简单的解决方案,它只使用 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

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

关于python - 将列表中的任何列表分配给字符串脚本。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33768758/

相关文章:

python - SpaCy TextCategorizer 管道详细信息

list - 关于在 Clojure 中创建列表的小问题

python - 从更高级别引发异常,a la warnings

python - 如果将带有 None 值的 *args 传递给 namedtuple 对象,则缺少必需的位置参数

javascript - 当你想抓取网页时,如果目标标签被省略号隐藏了怎么办?

java将字符串数据映射到python中的字典

python - PIL 从 I;16 转换为 JPEG 产生白色图像

python - 更新记分员

Python 列表规范化

c# - 如何从列表中获取特定范围(3 - 7)内的项目?