2015-11-17 93 views
1

我正在從第4章開始使用Python自動化鑽孔工具。下面是該項目的提示:將列表中的任何列表分配給字符串腳本。

「對於實踐,編寫程序來執行以下任務逗號碼 假設你有一個列表值是這樣的:垃圾= [」蘋果,‘香蕉’, ‘豆腐’ ,'cats']編寫一個將列表值作爲參數 的函數,並返回一個字符串,其中包含所有由逗號分隔的所有項目 以及一個空格,並在最後一項之前插入並插入空格。例如, 傳遞前一個垃圾郵件該函數列表將返回'蘋果, 香蕉,豆腐和貓',但是您的函數應該能夠將 與任何傳遞給它的列表值一起使用。「

我寫了一個腳本,在最後一項之前創建一個包含逗號和'and'的列表:但我無法弄清楚如何使腳本與傳遞給它的任何列表值一起工作。我試過使用輸入函數來調用列表,但這不起作用(或我無法工作),因爲輸入函數只接收字符串而不是列表名稱?

下面是我得到的最遠:

def listToString(list): 
    if list[-1]: 
     list.append('and '+str(list[-1])) 
     list.remove(list[-2]) 
    for i in range(len(list)): 
     print(''+list[i]+', ') 

spam = ['apples', 'bananas', 'tofu', 'cats'] 
listToString(spam) 

至於使用輸入()函數,這是我一直在努力,都無濟於事的代碼。我在shell編輯器中輸入的垃圾郵件列表,並運行此:

def listToString(list): 
    if list[-1]: 
     list.append('and '+str(list[-1])) 
     list.remove(list[-2]) 
    for i in range(len(list)): 
     print(''+list[i]+', ') 

list = input("What list do you want to use?") 
listToString(list) 
+1

此功能未指定。一個空的列表沒有最後一個元素,'['apples']'可能不應該變成''和'蘋果','['蘋果','香蕉']'可能不應該有逗號輸出。 – user2357112

回答

3

我認爲,最簡單的方法就是用替換的最後一個元素「和......」,然後加入與一切「」

def merge(list): 
    return ', '.join(list[:-1] + ['and '+list[-1]]) 
1

我相信「但是你的函數應該能夠處理傳遞給它的任何列表值。」意味着你不應該在函數中硬編碼示例列表(['蘋果','香蕉','豆腐','貓'))。

因此,該功能的最簡單的形式是:

def listToString(list): 
    return "{} and {}".format(", ".join(list[:-1]]), list[-1]) 

但是當你要處理其它類型不是字符串和少於2個元素,函數變爲:

def listToString(list): 
    length = len(list) 
    if length == 0 : 
     return "" 
    elif length == 1 : 
     return "{}".format(list[0]) 
    else: 
     strings = ["{}".format(x) for x in list[:-1]] 
     return "{} and {}".format(", ".join(strings), list[-1]) 
0

以下是我解決這個問題的方法。連同我對每行代碼的評論。希望這可以幫助。

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

# function should return 'apples, bananas, tofu, and cats' 

def listToString(list): 

    newString = '' # create an empty string variable 

    # for loop that iterates through length of list 
    for index in range(len(list)): 
     # put a comma and space after each word except the last one 
     if index in range(len(list)-1): 
      newString += list[index] + ',' + ' ' 
     else: 
      newString += 'and' + ' ' #put the word and + a space 
      #finally put the last word from the list 
      #spam in the string newString 
      newString += list[index] 

     #return newString value 
     return '{}'.format(newString) 

listToString(spam) 

輸出:

'apples, bananas, tofu, and cats' 
1

該解決方案完全基於掩蓋了第4章。它使大量使用在第3章提出的「結束」參數的基本原則。

spam = ['apples', 'bananas', 'tofu', 'cats'] 
print("'", end='') 
for i in range(len(spam)-1): 
    print(spam[i], end=', ') 
print('and '+str(spam[-1]), end='') 
print("'") 
1

這裏是我的解決方案:

spam = ['zero', 'one', 'two', 'three', 'second to last', 'last'] 

def func(listValue): 
    print('\'', end='') # Openning single quote. 
    for i in range(len(listValue[:-2])): # Iterate through all values in the list up to second to last. 
     print(str(listValue[i]), end=', ') 
     continue 
    print(str(listValue[-2]) + ' and ' + str(listValue[-1]) + '\'') # Add second to last and last to string separated by 'and'. End with a single quote. 

listValue = spam 
func(listValue) 

    # Will do for any list. 

輸出是:

'零,一,二,三,倒數第二個和最後一個'

0

這裏是我想出瞭解決方案經過一週的學習python:

spam = ['apples', 'bananas', 'tofu', 'cats', 'rats', 'turkeys'] 
group = [] 
for i in range(len(spam)-1): 
    group.append(spam[i]) 
print (', '.join(group),'& ' +spam[-1]) 

我剛剛在我的新python愛好期間正在處理這個問題。

我知道我的解決方案不像頂級的解決方案那麼緊湊和優雅。我基本上只是使用for語句創建了第二個不帶最後一個條目的列表,然後使用打印加入該組添加了「&」符號,最後是最後一個條目。

+1

而不是'for'循環,這會更簡單的做'print(','.join(spam [: - 1]),'&'+ spam [-1]),回答。 'spam [: - 1]'是沒有最後一個條目的列表。請參閱[切分](https://docs.python.org/2/tutorial/introduction.html#strings),它對於字符串與列表的作用相同。按Ctrl + F並輸入「Slice」。 – mbomb007

3

這裏有一個簡單的解決方案只使用已經Chapter 4涵蓋語法:

def toString(arr): 
    s = '' 
    for i in range(len(arr)): 
     if i > 0: 
      if i == len(arr) - 1: 
       # last one 
       s = s + ' and ' 
      else: 
       # second, third, ... 
       s = s + ', ' 
     s = s + arr[i]; 
    return s 

它適用於任何數量的元素的數組。

0

這就是我想出來的。

spam = ['apples', 'bananas', 'tofu', 'cats'] 
spam.insert(-1, ' and') 
print(spam[0] + ', ' + spam[1] + ', ' + spam[2] + ',' + spam[3] + ' ' + spam[4]) 
0

這是我的解決方案

def converter(mylist): 
    mystr='' 
    if len(mylist)>1: 
     for i in range(len(mylist)-1): 
      mystr=mystr+str(mylist[i])+', ' 
     mystr=mystr+'and '+str(mylist[-1]) 
     print(mystr) 
    elif len(mylist)==1:  
     mystr=mystr+str(mylist[0]) 
     print(mystr) 
    else: 
     print('Your list is empty') 
spam = [] 
t='1' 
while t != '': 
    print('Input new value in list (Or enter nothing to stop)') 
    t=str(input()) 
    if t != '': 
     spam.append(t) 
converter(spam) 
0

我的逗號代碼的版本:

spam = ['apples', 'bananas', 'tofu', 'cats'] 
newList = [] 
myString = '' 

def comma(aList): 
    for i in range(len(aList) - 1): 
     newList.append(aList[i]) 
    newList.append('and ') 
    myString = ', '.join(newList) 
    print(myString + aList[-1]) 

comma(spam) 
0

按照轉讓時,必須確保「的功能應該能夠與任何合作列表值傳遞給它。「這意味着它必須使用0,1,1 +列表值。

spam = ['green','eggs','ham'] 

def merge(list): 
    if len(list) == 0: 
     return None 
    elif len(list) == 1: 
     return list[0] 
    else: 
     return ', '.join(list[:-1] + ['and '+list[-1]]) 

print(merge(spam)) 
相關問題