2016-09-30 52 views
2

我一直在爲此工作兩天。這就是分配狀態:打印用逗號分隔的項目列表,但在最後一個項目前加上「and」。

說你有一個這樣的列表值:listToPrint = ['apples', 'bananas', 'tofu', 'cats']編寫打印所有用逗號和空格分隔的項目,以「和」前的最後插入一個列表的程序項目。例如,上面的列表將打印'apples, bananas, tofu, and cats'。但是你的程序應該能夠處理任何列表,而不僅僅是上面顯示的列表。因此,如果要打印的列表比上述列表更短或更長,則需要使用循環。

這是我迄今:

listToPrint = [] 
while True: 
    newWord = input("a, b, and c ") 
    if newWord == "": 
     break 
    else: 
     listToPrint.append(newWord) 
+0

你有什麼具體問題?你在上面使用的'whilewhile'循環應該做你描述的。 –

+0

謝謝你的迴應Rick。這就是我的想法,但這似乎太簡單了。所以,如果我要添加到列表中,我會插入它,以及如何?我是否會繼續增加或減少輸入?列表不應該保留在某個地方的全局列表中嗎?我很新,所以我有點困惑。 – tinabina22

+0

我明白作爲初學者很難提出正確的問題,但我也很難理解你遇到的問題。輸入行和行'listToPrint.append(newWord)'每次發生循環時執行。它們在while循環的內部。每次執行該主體直到遇到「break」。 –

回答

0

這裏是我會怎麼做,但要小心,如果這是學校。如果我在下面做的任何事情正在使用尚未涵蓋的功能或技術,那麼您的教師將對您皺眉。

listToPrint = ['a', 'b', 'c'] 

def list_to_string(L, sep = '', last_sep = None): 
    if last _sep is None: 
     return sep.join(L) 
    else: 
     return sep.join(L[:-1]) + last_sep + L[-1] 

print(list_to_string(listToPrint, sep = ', ', last_sep = ', and ')) 

這裏有更多的初學者版位:

listToPrint = ['a', 'b', 'c'] 
list_length = len(listToPrint) 

result = "" 
count = 0 
for item in listToPrint: 
    count = count + 1 
    if count == list_length: 
     result = result + "and " + item 
    else: 
     result = result + item + ", " 

這其中不只有一個列表中的項目工作。

1

您顯示的代碼似乎解決了與您的任務希望您執行的操作不同的問題。分配的重點是print提供的list中的值,而您的代碼全部來自用戶的項目並將其放入列表中。做一個,然後做另一個是有道理的,但是對於你在評論中給出的任務,input代碼是完全不相關的。

以下是我想解決這個任務(可能與代碼,你還不知道):

print("{}, and {}".format(", ".join(list_to_print[:-1]), list_to_print[-1])) 

更「新手友好」的做法更像是這樣的:

for item in list_to_print[:-1]: 
    print(item, end=', ') 
print('and', list_to_print[-1]) 
+0

非常感謝,這個工作。對於list_to_print [: - 1]中的項目,打印('item',end =',') print – tinabina22

-1

初級版本:

x = ['apples', 'bananas', 'tofu', 'cats'] 

print("'", end='') 

for i in range(len(x)-2): 

    print(x[i], end=', ') 

print(str(x[-2])+' and '+str(x[-1]),end='') 

print("'") 

輸出:'apples, bananas, tofu and cats'

-1
#printing the first element sep. so the list works  
print(listToPrint[0], end="") 

for i in range(1, len(listToPrint)-1): 

    print("," + listToPrint[i], end="") #this prints the middle elements 

if(len(listToPrint) > 1): 

    print(" and " + listToPrint[-1], end="") 
相關問題