[英]Is there a shorter way to write Comma Code?
I am working on the practice projects in chapter 4 of Automate the boring stuff with Python
. 我正在“ Automate the boring stuff with Python
第4章中的练习项目上工作。
In the Comma Code 'practice projects'
, it asks you to 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. 在逗号代码'practice projects'
,它要求您编写一个函数,该函数以列表值作为参数,并返回一个字符串,其中所有项目均以逗号和空格分隔,并在最后一项之前插入并插入。
Is there a shorter way to write this code? 有没有编写此代码的较短方法?
I have defined my function and used a for
loop with range(len(list))
to iterate over the index of the list. 我已经定义了我的函数,并使用了一个带有range(len(list))
的for
循环来遍历列表的索引。
then I named my list and added some items to it. 然后我命名了清单并添加了一些项目。
I finished by calling the list. 我通过致电名单结束了。
def carpenter(Powertools):
for i in range(len(Powertools)-1):
print(Powertools[i] + ',', end='')
ToolBox = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
carpenter(ToolBox)
print(' and ' + ToolBox[-1])
The output gave me the list items I wanted, with and inserted by the last item. 输出给我的列表中的项目,我想,与和最后一个项目插入。
But I was wondering, is there a shorter way to write this code? 但是我想知道,是否有更短的编写代码的方法?
You can use a list comprehension inside join
like this and append and
followed by last item. 您可以像这样在join
内使用列表推导and
然后追加and
最后一个项目。
', '.join(x for x in ToolBox[:-1]) + ' and ' + ToolBox[-1]
Putting this to function can be done like this, 可以像这样将其发挥作用,
def carpenter(power_tools):
return ', '.join(x for x in power_tools[:-1]) + ' and ' + power_tools[-1]
tool_box = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
joined = carpenter(tool_box)
print(joined) # hammer, chisel, wrench, measuring tape and screwdriver
Note that I have changed the variable names following PEP-8. 请注意,我在PEP-8之后更改了变量名称。
Also, there is no need for comprehension, you can do something like this for the same result. 同样,也不需要理解,您可以为相同的结果执行类似的操作。
def carpenter(power_tools):
return ', '.join(power_tools[:-1]) + ' and ' + power_tools[-1]
tool_box = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
joined = carpenter(tool_box)
print(joined) # hammer, chisel, wrench, measuring tape and screwdriver
Use join() to make comma separated list and slice list until second last element and use string .format() for for combining last element 使用join()以逗号分隔列表和切片列表,直到倒数第二个元素为止,并使用字符串.format()合并最后一个元素
def carpenter(Powertools):
finalresult=",".join(Powertools[:-1])
print('{} and {}'.format(finalresult,Powertools[-1]))
ToolBox = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
carpenter(ToolBox)
Result: 结果:
hammer,chisel,wrench,measuring tape and screwdriver
This should work: 这应该工作:
def carpenter(powertools):
return ','.join(powertools[:-1]) + ' and ' + powertools[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.