将列表中的任何列表分配给字符串脚本. [英] Assigning any list in a list to string script.

查看:73
本文介绍了将列表中的任何列表分配给字符串脚本.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究用Python自动化乏味的东西"第4章中的项目.这是项目的提示:

I'm working on a project from Chapter 4 of Automate the Boring Stuff with Python. Here's the project's prompt:

作为练习,编写程序来执行以下任务.逗号代码 假设您有一个这样的清单值:spam = ['apples','bananas, ''tofu','cats']编写一个将列表值作为 参数并返回一个字符串,其中所有项目均以逗号分隔 和一个空格,在最后一项之前插入和.例如, 将先前的垃圾邮件列表传递给该函数将返回'apples, 香蕉,豆腐和猫.但是您的功能应该可以正常工作 以及传递给它的任何列表值."

"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'创建一个列表:但是我不知道如何使该脚本与传递给它的任何列表值一起使用.我尝试使用输入函数调用列表,但这不起作用(或者我无法工作),因为输入函数仅接收字符串而不接收列表名称?

I wrote a script that creates a list with commas and an 'and' before the last item: But I can't figure out how to make the script work with any list value passed to it. I've tried using the input function to call a list, but that doesn't work (or I can't get to work), since the input function only receives strings and not list names?

这是我走得最远的地方:

Here's the farthest I've gotten:

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()函数而言,这是我尝试无效的代码.我在外壳编辑器中输入垃圾邮件列表,然后运行以下命令:

As far as using the input() function, here's the code I've tried to no avail. I enter the spam list in the shell editor and run this:

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)

推荐答案

这是一个简单的解决方案,仅使用第四章:

Here's a simple solution which only uses syntax already covered by 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

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

It works for arrays with any number of elements.

这篇关于将列表中的任何列表分配给字符串脚本.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆