我正在处理《使用 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/