Python 将列表中的任何列表分配给字符串脚本。
我正在从事《用Python自动化无聊的东西》第4章中的一个项目。以下是该项目的提示: 为了练习,请编写程序来执行以下任务。逗号代码 假设您有这样一个列表值:spam=['苹果','香蕉', ‘tofu’、‘cats’]编写一个函数,将列表值作为 参数,并返回一个字符串,其中所有项都用逗号分隔 和一个空格,在最后一项之前插入和。例如, 将以前的垃圾邮件列表传递给函数将返回“apples, 香蕉、豆腐和猫。但你的功能应该可以发挥作用 将任何列表值传递给它。” 我编写了一个脚本,在最后一项之前创建了一个带有逗号和“and”的列表:但我不知道如何使脚本在任何列表值传递给它的情况下工作。我曾尝试使用输入函数调用列表,但这不起作用(或者我无法开始工作),因为输入函数只接收字符串而不接收列表名称 这是我得到的最远的结果:Python 将列表中的任何列表分配给字符串脚本。,python,list,python-3.x,Python,List,Python 3.x,我正在从事《用Python自动化无聊的东西》第4章中的一个项目。以下是该项目的提示: 为了练习,请编写程序来执行以下任务。逗号代码 假设您有这样一个列表值:spam=['苹果','香蕉', ‘tofu’、‘cats’]编写一个函数,将列表值作为 参数,并返回一个字符串,其中所有项都用逗号分隔 和一个空格,在最后一项之前插入和。例如, 将以前的垃圾邮件列表传递给函数将返回“apples, 香蕉、豆腐和猫。但你的功能应该可以发挥作用 将任何列表值传递给它。” 我编写了一个脚本,在最后一项之前创建了一
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)
我认为最简单的方法是用“and…”替换最后一个元素,然后用“,”连接所有元素
我认为最简单的方法是用“and…”替换最后一个元素,然后用“,”连接所有元素 我相信“但是您的函数应该能够处理传递给它的任何列表值。”这意味着您不应该在函数中硬编码示例列表(['apples','pananas','tofu','cats')) 因此,函数的最简单形式是:
def listToString(list):
return "{} and {}".format(", ".join(list[:-1]]), list[-1])
但如果要处理字符串以外的其他类型且元素少于2个,则函数将变为:
def listToString(list):
length = len(list)
if length == 0 :
return ""
elif length == 1 :
return "{}".format(list[0])
else:
strings = ["{}".format(x) for x in list[:-1]]
return "{} and {}".format(", ".join(strings), list[-1])
我相信“但是您的函数应该能够处理传递给它的任何列表值。”这意味着您不应该在函数中硬编码示例列表(['apples','pananas','tofu','cats'))
因此,函数的最简单形式是:
def listToString(list):
return "{} and {}".format(", ".join(list[:-1]]), list[-1])
但如果要处理字符串以外的其他类型且元素少于2个,则函数将变为:
def listToString(list):
length = len(list)
if length == 0 :
return ""
elif length == 1 :
return "{}".format(list[0])
else:
strings = ["{}".format(x) for x in list[:-1]]
return "{} and {}".format(", ".join(strings), list[-1])
下面是我对这个问题的解决方案。以及我对每行代码的注释。希望这有帮助
spam = ['apples', 'bananas', 'tofu', 'cats']
# function should return 'apples, bananas, tofu, and cats'
def listToString(list):
newString = '' # create an empty string variable
# for loop that iterates through length of list
for index in range(len(list)):
# put a comma and space after each word except the last one
if index in range(len(list)-1):
newString += list[index] + ',' + ' '
else:
newString += 'and' + ' ' #put the word and + a space
#finally put the last word from the list
#spam in the string newString
newString += list[index]
#return newString value
return '{}'.format(newString)
listToString(spam)
输出:
'apples, bananas, tofu, and cats'
下面是我对这个问题的解决方案。以及我对每行代码的注释。希望这有帮助
spam = ['apples', 'bananas', 'tofu', 'cats']
# function should return 'apples, bananas, tofu, and cats'
def listToString(list):
newString = '' # create an empty string variable
# for loop that iterates through length of list
for index in range(len(list)):
# put a comma and space after each word except the last one
if index in range(len(list)-1):
newString += list[index] + ',' + ' '
else:
newString += 'and' + ' ' #put the word and + a space
#finally put the last word from the list
#spam in the string newString
newString += list[index]
#return newString value
return '{}'.format(newString)
listToString(spam)
输出:
'apples, bananas, tofu, and cats'
此解决方案完全基于第4章所述的基本原则。它充分利用了第3章中给出的“end”参数
spam = ['apples', 'bananas', 'tofu', 'cats']
print("'", end='')
for i in range(len(spam)-1):
print(spam[i], end=', ')
print('and '+str(spam[-1]), end='')
print("'")
此解决方案完全基于第4章所述的基本原则。它充分利用了第3章中给出的“end”参数
spam = ['apples', 'bananas', 'tofu', 'cats']
print("'", end='')
for i in range(len(spam)-1):
print(spam[i], end=', ')
print('and '+str(spam[-1]), end='')
print("'")
以下是我的解决方案:
spam = ['zero', 'one', 'two', 'three', 'second to last', 'last']
def func(listValue):
print('\'', end='') # Openning single quote.
for i in range(len(listValue[:-2])): # Iterate through all values in the list up to second to last.
print(str(listValue[i]), end=', ')
continue
print(str(listValue[-2]) + ' and ' + str(listValue[-1]) + '\'') # Add second to last and last to string separated by 'and'. End with a single quote.
listValue = spam
func(listValue)
# Will do for any list.
输出为:
“零、一、二、三、倒数第二和倒数第二”这是我的解决方案:
spam = ['zero', 'one', 'two', 'three', 'second to last', 'last']
def func(listValue):
print('\'', end='') # Openning single quote.
for i in range(len(listValue[:-2])): # Iterate through all values in the list up to second to last.
print(str(listValue[i]), end=', ')
continue
print(str(listValue[-2]) + ' and ' + str(listValue[-1]) + '\'') # Add second to last and last to string separated by 'and'. End with a single quote.
listValue = spam
func(listValue)
# Will do for any list.
输出为:
“零、一、二、三、倒数第二和倒数第二”这是我在学习python一周后提出的解决方案:
spam = ['apples', 'bananas', 'tofu', 'cats', 'rats', 'turkeys']
group = []
for i in range(len(spam)-1):
group.append(spam[i])
print (', '.join(group),'& ' +spam[-1])
在我的新python爱好中,我今天正在研究这个问题
我知道我的解决方案没有顶级解决方案那么紧凑和优雅。基本上,我只是使用for语句创建了第二个列表,其中没有最后一个条目,然后使用print加入该组,添加“&”符号,最后添加最后一个条目。学习python一周后,我提出了以下解决方案:
spam = ['apples', 'bananas', 'tofu', 'cats', 'rats', 'turkeys']
group = []
for i in range(len(spam)-1):
group.append(spam[i])
print (', '.join(group),'& ' +spam[-1])
在我的新python爱好中,我今天正在研究这个问题
我知道我的解决方案没有顶级解决方案那么紧凑和优雅。我基本上只是使用for语句创建了第二个列表,其中没有最后一个条目,然后使用print加入该组,添加“&”符号,最后添加最后一个条目。这里有一个简单的解决方案,它只使用以下语法:
它适用于具有任意数量元素的数组。这里有一个简单的解决方案,它只使用以下内容中已经介绍的语法:
它适用于具有任意数量元素的数组。这就是我想到的
spam = ['apples', 'bananas', 'tofu', 'cats']
spam.insert(-1, ' and')
print(spam[0] + ', ' + spam[1] + ', ' + spam[2] + ',' + spam[3] + ' ' + spam[4])
这就是我想到的
spam = ['apples', 'bananas', 'tofu', 'cats']
spam.insert(-1, ' and')
print(spam[0] + ', ' + spam[1] + ', ' + spam[2] + ',' + spam[3] + ' ' + spam[4])
这是我的解决办法
def converter(mylist):
mystr=''
if len(mylist)>1:
for i in range(len(mylist)-1):
mystr=mystr+str(mylist[i])+', '
mystr=mystr+'and '+str(mylist[-1])
print(mystr)
elif len(mylist)==1:
mystr=mystr+str(mylist[0])
print(mystr)
else:
print('Your list is empty')
spam = []
t='1'
while t != '':
print('Input new value in list (Or enter nothing to stop)')
t=str(input())
if t != '':
spam.append(t)
converter(spam)
这是我的解决办法
def converter(mylist):
mystr=''
if len(mylist)>1:
for i in range(len(mylist)-1):
mystr=mystr+str(mylist[i])+', '
mystr=mystr+'and '+str(mylist[-1])
print(mystr)
elif len(mylist)==1:
mystr=mystr+str(mylist[0])
print(mystr)
else:
print('Your list is empty')
spam = []
t='1'
while t != '':
print('Input new value in list (Or enter nothing to stop)')
t=str(input())
if t != '':
spam.append(t)
converter(spam)
逗号代码的我的版本:
spam = ['apples', 'bananas', 'tofu', 'cats']
newList = []
myString = ''
def comma(aList):
for i in range(len(aList) - 1):
newList.append(aList[i])
newList.append('and ')
myString = ', '.join(newList)
print(myString + aList[-1])
comma(spam)
逗号代码的我的版本:
spam = ['apples', 'bananas', 'tofu', 'cats']
newList = []
myString = ''
def comma(aList):
for i in range(len(aList) - 1):
newList.append(aList[i])
newList.append('and ')
myString = ', '.join(newList)
print(myString + aList[-1])
comma(spam)
根据分配,您必须确保“您的函数应该能够使用传递给它的任何列表值。”这意味着它必须使用0、1、1+列表值
spam = ['green','eggs','ham']
def merge(list):
if len(list) == 0:
return None
elif len(list) == 1:
return list[0]
else:
return ', '.join(list[:-1] + ['and '+list[-1]])
print(merge(spam))
根据分配,您必须确保“您的函数应该能够使用传递给它的任何列表值。”这意味着它必须使用0、1、1+列表值
spam = ['green','eggs','ham']
def merge(list):
if len(list) == 0:
return None
elif len(list) == 1:
return list[0]
else:
return ', '.join(list[:-1] + ['and '+list[-1]])
print(merge(spam))
这里有一个非常简单的解决方案:
def lst2str(spam):
str = ''
for word in spam:
if word != spam[-1]:
spacing = word + ", "
str += spacing
else:
spacing = "and " + word
str += spacing
return str
这里有一个非常简单的解决方案:
def lst2str(spam):
str = ''
for word in spam:
if word != spam[-1]:
spacing = word + ", "
str += spacing
else:
spacing = "and " + word
str += spacing
return str
此函数未指定。空列表没有最后一个元素,
['apples']
可能不应该变成,而apples'
,['apples',bananas']
可能不应该在输出中有逗号。此函数未指定。空列表没有最后一个元素,['apples']
可能不应该变成,而apples'
,['apples',bananas']
可能不应该在输出中有逗号。与其使用for
循环,不如使用打印(','.join(spam[:-1]),“&++spam[-1])
,这基本上是最好的答案<代码>垃圾邮件[:-1]是没有最后一项的列表。请参见,它对字符串的作用与对列表的作用相同。按ctrl+F键并键入“Slice”。对于循环,使用打印(','.join(spam[:-1]),'&'+spam[-1])
更简单,这基本上是最重要的答案<代码>垃圾邮件[:-1]是没有最后一项的列表。请参见,它对字符串的作用与对列表的作用相同。按ctrl+F键并键入“切片”。