用Python自动化那些无聊的东西。逗号代码
在用Python自动化枯燥的东西中,有一个叫做逗号代码的实践项目: 假设您有如下列表值:用Python自动化那些无聊的东西。逗号代码,python,Python,在用Python自动化枯燥的东西中,有一个叫做逗号代码的实践项目: 假设您有如下列表值: spam = ['apples', 'bananas', 'tofu', 'cats'] 编写一个函数,将列表值作为参数并返回 一个字符串,其中所有项目由逗号和空格分隔,并带有“and” 插入到最后一项之前。例如,将以前的垃圾邮件列表传递给 函数将返回“苹果、香蕉、豆腐和猫”。但是你的功能呢 应该能够处理传递给它的任何列表值 这是我做的: y = ['apples', 'bananas', 'tofu',
spam = ['apples', 'bananas', 'tofu', 'cats']
编写一个函数,将列表值作为参数并返回
一个字符串,其中所有项目由逗号和空格分隔,并带有“and”
插入到最后一项之前。例如,将以前的垃圾邮件列表传递给
函数将返回“苹果、香蕉、豆腐和猫”。但是你的功能呢
应该能够处理传递给它的任何列表值
这是我做的:
y = ['apples', 'bananas', 'tofu', 'cats']
def function(x):
x.insert(-1, ('and ' + x[-1]))
del x[-1]
numbers = len(x)
spam = x[0]
for i in range(1,numbers):
spam = spam + ', ' + x[i]
print(spam)
function(y)
该函数可以处理任何列表值,我已经完成了它所要求的所有操作,但我想知道的是,是否有更好的方法来执行此操作,或者它是否要求与此不同的内容。我也想知道我的代码有什么不好的地方。几天前我开始读这本书,所以我对编码完全陌生。这是你第一次编码,为什么不这样做呢?这是你可以理解和“感觉直观”的东西
请注意,如果您只有一个项目,它将打印为
和最后一个项目
非常基本的方法,这就是我喜欢它的原因:
a = ", ".join(y[:-1]) + " and " + y[-1]
加入
除最后一个元素外的所有列表元素,并通过字符串添加来添加此元素
spam = ['apples', 'bananas', 'tofu', 'cats']
def makeString(l):
stringPart1 = l[:-1]
stringPart2 = l[-1]
finalString = ', '.join(stringPart1)+' and '+stringPart2
return finalString
print(makeString(spam))
结果
apples, bananas, tofu and cats
# stringPart1 will be a list consist of following elements.
# stringPart1 = ['apples', 'bananas', 'tofu']
# 1[:-1] slice every thing from the 0 to last-1
#
# stringPart2 will be a string.
# stringPart2 = 'cats'
# 1[-1] = return the item at the last index
我想到了解决方案:
# do add conditions to return list if len is <2
# perhaps return " and ".join(l) if len == 2
" ".join([", ".join(l[:-1] + ["and"]), l[-1]])
'a, b, and c'
#如果len是,请在返回列表中添加条件这是一个非常简单的问题解决方案:
spam = ['apples', 'bananas', 'tofu', 'cats']
def items(things):
for i in range(len(things) - 1):
print(things[i] + ', ', end='')
print('and ' + things[-1])
items(spam)
这是我的代码:
spam = ['apples', 'bananas', 'tofu', 'cats']
def what_in_list(spam):
spam[-1] = 'and ' + spam[-1]
content_in_list = ''
for i in spam:
content_in_list += i + ',' + ' '
print("'" + content_in_list[:-2] + "'.")
what_in_list(spam)
仅使用您从“用Python自动化无聊的东西”中了解的内容
我已经想出了一个相当简单的代码来解决这个问题。请看一看
spam = ['apples', 'bananas', 'tofu', 'cats']
def list_to_string(value):
value.insert(len(value)-1,'and')
st = '' #empty string
for i in value:
st = st + ', ' + i #to concatenate the list values to a single string
print st.lstrip(', ') #lstrip - to strip off the comma and space at the beginning of the string
list_to_string(spam) #calling the function
我在这段代码中发现的唯一问题是,我无法删除“and”之后的逗号
另一方面,代码运行良好
谢谢。定义逗号代码(逗号列表):
给定的_列表=[‘苹果’、‘香蕉’、‘豆腐’、‘猫’]
逗号代码(给定列表)我知道这是一个老问题,但我也只是在学习用这本书编写代码。下面是我使用本书、堆栈溢出和各种其他资源编写的代码。我是一个初学者,所以它是什么。我相信有一种更有效的代码可以做到这一点
这段代码将继续询问添加、删除和重述问题,以便您可以继续调整列表。直到你辞职
import sys
myList = ['apples', 'bananas', 'tofu', 'cats']
def items(myList):
for i in range(len(myList) - 1):
print(myList[i] + ', ', end ='')
print('and ' + myList[-1])
def change():
while True:
print() #print() gives it a blank space
n = input("""
Do you want to add or remove from the list?
Do you want to restate the list?
Type N to exit,
Y for adding,
R to remove
L to restate list. """)
print()
if n.lower() =='y':
print()
myList.insert(0, input('Insert what you want to add. '))
elif n.lower() == 'r':
print()
name = input('Input item name you wish to remove. ')
if name in myList:
myList.remove(name)
elif n.lower() == 'l':
items(myList)
elif n.lower() == 'n':
sys.exit()
items(myList)
change()
还有另一种为该任务编译简单代码的简单方法:
def CommaCode(list):
h = list[-2] + ' and ' + list[-1]
for i in list[0:len(list)-2]:
print(str(i), end = ', ')
print(h)
如果您使用垃圾邮件列表运行它来检查:
CommaCode(spam)
apples, bananas, tofu and cats
这是解决此问题的最简单代码
array = ['apples', 'bananas', 'tofu', 'cats']
def commaCode (array):
print("'"+ array[0]+',',end= '') #this line for the first element
for i in range (1,len(array)-1): #iteration for the elements from 1 until n-1
print(array[i]+',',end='')
print('and '+array[-1]+"'") #this for the last element
commaCode(array)
这是我的密码。我知道可以改进,但我只是个初学者。如果有人提供建设性意见,我将不胜感激
spam = ['apples', 'bananas', 'tofu', 'cats']
def commaSpace(listValue):
for i in range(len(listValue)):
print(listValue[i] + ', ' , end='')
if listValue[i] == listValue[-1]:
print('and ' + listValue[-1])
commaSpace(spam)
我是一个初学者,但最实用的解决方案似乎是使用“加入”方法。
我的尝试:
def concac(arg):
words = ''
for i in arg:
words += i
new = ",".join(arg[0:len(arg)-1]) + " and " + arg[-1]
return new
欢迎来到堆栈溢出!我投票结束这个问题,因为这对于堆栈溢出来说实在是太宽泛了,堆栈溢出处理的是比这更集中的编码问题。有关改善工作代码的建议,请考虑——但请先阅读。我会赞成保留你的牛津逗号的第一个答案:)我同意其他的说法。完全工作的代码应该发布在代码审查上,而不是StackOverflow上。我建议这样做。这涉及到检查工作代码的风格,并且可能更适合于。Stack Overflow专门处理无效代码。欢迎使用Stack Overflow,请查看:感谢您提供此代码段,它可能会提供一些有限的即时帮助。一个恰当的解释将通过说明为什么这是一个很好的问题解决方案而大大提高它的长期价值,并将使它对未来有其他类似问题的读者更有用。请编辑您的答案,添加一些解释,包括您所做的假设。
array = ['apples', 'bananas', 'tofu', 'cats']
def commaCode (array):
print("'"+ array[0]+',',end= '') #this line for the first element
for i in range (1,len(array)-1): #iteration for the elements from 1 until n-1
print(array[i]+',',end='')
print('and '+array[-1]+"'") #this for the last element
commaCode(array)
spam = ['apples', 'bananas', 'tofu', 'cats']
def commaSpace(listValue):
for i in range(len(listValue)):
print(listValue[i] + ', ' , end='')
if listValue[i] == listValue[-1]:
print('and ' + listValue[-1])
commaSpace(spam)
def concac(arg):
words = ''
for i in arg:
words += i
new = ",".join(arg[0:len(arg)-1]) + " and " + arg[-1]
return new