<p>我正在做第4章中的一个项目,用Python自动化那些无聊的东西。以下是项目提示:</p>
<blockquote>
<p>"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."</p>
</blockquote>
<p>我编写了一个脚本,它在最后一项之前创建一个带有逗号和“and”的列表:但是我不知道如何在传递给它的任何列表值的情况下使脚本工作。我尝试过使用input函数来调用list,但这不起作用(或者我无法工作),因为input函数只接收字符串而不接收列表名称?在</p>
<p>以下是我所得到的最远距离:</p>
<pre><code>def listToString(list):
if list[-1]:
list.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>('and '+str(list[-1]))
list.remove(list[-2])
for i in range(len(list)):
print(''+list[i]+', ')
spam = ['apples', 'bananas', 'tofu', 'cats']
listToString(spam)
</code></pre>
<p>至于使用input()函数,下面是我尝试过的没有用的代码。我在shell编辑器中输入垃圾邮件列表并运行以下命令:</p>
^{pr2}$