繁体   English   中英

有没有更短的编写逗号代码的方法?

[英]Is there a shorter way to write Comma Code?

我正在“ Automate the boring stuff with Python第4章中的练习项目上工作。
在逗号代码'practice projects' ,它要求您编写一个函数,该函数以列表值作为参数,并返回一个字符串,其中所有项目均以逗号和空格分隔,并在最后一项之前插入并插入。

有没有编写此代码的较短方法?

我已经定义了我的函数,并使用了一个带有range(len(list))for循环来遍历列表的索引。

然后我命名了清单并添加了一些项目。

我通过致电名单结束了。

 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])

输出给我的列表中的项目,我想,与最后一个项目插入。
但是我想知道,是否有更短的编写代码的方法?

您可以像这样在join内使用列表推导and然后追加and最后一个项目。

', '.join(x for x in ToolBox[:-1]) + ' and ' + ToolBox[-1]

可以像这样将其发挥作用,

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

请注意,我在PEP-8之后更改了变量名称。

同样,也不需要理解,您可以为相同的结果执行类似的操作。

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

使用join()以逗号分隔列表和切片列表,直到倒数第二个元素为止,并使用字符串.format()合并最后一个元素

def carpenter(Powertools):
  finalresult=",".join(Powertools[:-1])
  print('{} and {}'.format(finalresult,Powertools[-1]))


ToolBox = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
carpenter(ToolBox)

结果:

hammer,chisel,wrench,measuring tape and screwdriver

这应该工作:

def carpenter(powertools):
    return ','.join(powertools[:-1]) + ' and ' + powertools[-1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM