Python 有没有一种更短的方法来编写逗号代码?
我正在从事Python 有没有一种更短的方法来编写逗号代码?,python,list,function,comma,Python,List,Function,Comma,我正在从事第4章中的实践项目,用Python自动化枯燥的东西 在逗号代码“实践项目”中,它要求您编写一个函数,该函数将列表值作为参数,并返回一个字符串,其中所有项目用逗号和空格分隔,最后一个项目前插入和 有没有更简短的方法来编写此代码 我已经定义了我的函数,并使用带有范围(len(list))的for循环来迭代列表的索引 def carpenter(Powertools): for i in range(len(Powertools)-1): print(Powertools[i]
第4章中的实践项目,用Python自动化枯燥的东西
在逗号代码“实践项目”
中,它要求您编写一个函数,该函数将列表值作为参数,并返回一个字符串,其中所有项目用逗号和空格分隔,最后一个项目前插入和
有没有更简短的方法来编写此代码
我已经定义了我的函数,并使用带有范围(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])
然后我命名了我的列表,并向其中添加了一些项目
最后我打电话给名单
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(工具箱[:-1]中的x代表x)+和'+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]
“”、”.join(工具箱[:-1])+”和“+ToolBox[-1]”中的x代表x
请您向我说明您将在代码中的何处编写这些代码,以澄清问题?