簡體   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