2016-08-16 55 views

回答

13

當有列表中的項目1+(如果沒有,只是使用的第一個元素):

>>> "{} and {}".format(", ".join(listy[:-1]), listy[-1]) 
'item1, item2, item3, item4, item5, and item6' 

編輯:如果你需要一個牛津逗號(不知道它甚至存在! ) - 只需使用:", and" isntead。

+1

**注**:對OP的例子使用了[牛津逗號(https://en.wikipedia.org/wiki/Serial_comma)。 – wim

+1

@wim:編輯我的答案.. – SuperSaiyan

+0

該解決方案僅適用於列表,不處理空或單元列表的情況,並使用'+'連接字符串,這是不鼓勵的,應該用' .format'。 – Daniel

1

在Python中,許多函數,與列表一起使用也可以與迭代器一起使用(如joinsumlist)。要獲得迭代的最後一項並不容易,因爲你無法獲得長度,因爲它可能未知。

def coma_iter(iterable): 
    sep = '' 
    last = None 
    for next in iterable: 
     if last is not None: 
      yield sep 
      yield last 
      sep = ', ' 
     last = next 
    if sep: 
     yield ', and ' 
    if last is not None: 
     yield last 

print ''.join(coma_iter(listy)) 
+0

@SerialDownvoter:您可以在您贊成的帖子上回復嗎?這是一個非常有效的答案。 – SuperSaiyan

+0

@SuperSaiyan哈哈'@SerialDownvoter' –

+0

這是我見過的最醜陋的Python代碼。 – wim

3
def coma(lst): 
    return '{} and {}'.format(', '.join(lst[:-1]), lst[-1]) 
3
def oxford_comma_join(l): 
    if not l: 
     return "" 
    elif len(l) == 1: 
     return l[0] 
    else: 
     return ', '.join(l[:-1]) + ", and " + l[-1] 

print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6'])) 

輸出:

item1, item2, item3, item4, item5, and item6 

同樣作爲預留Python化的方式來寫

for i in abc[0:-1]: 

for i in abc[:-1]: 
+0

讚賞的解釋讚賞 –

+0

這不應該有downvote。這很清楚,而且是唯一真正符合OP要求的答案。 +1 –

1

組合字符串時使用+通常是不好的做法,因爲它通常很慢。相反,你可以使用

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

你必須留意的是,這將打破,如果你只有一個項目:

>>> comma(["spam"]) 
', and spam' 

爲了解決這個問題,你可以測試列表的長度( if len(items) >= 2:),或做到這一點,它(恕我直言)稍微更Python:

def comma(items): 
    start, last = items[:-1], items[-1] 

    if start: 
     return "{}, and {}".format(", ".join(start), last) 
    else: 
     return last 

正如我們上面看到的,將導致items[:-1]空值的單個項目列表。 if last:只是檢查last是否爲空的pythonic方式。

+0

對於Python 3,您可以使用'* start,last = items' – RootTwo

1

也可以用遞歸示例展示解決方案。

>>> listy = ['item1', 'item2','item3','item4','item5', 'item6'] 
>>> def foo(a): 
    if len(a) == 1: 
     return ', and ' + a[0] 
    return a[0] + ', ' + foo(a[1:]) 

>>> foo(listy) 
'item1, item2, item3, item4, item5, , and item6' 
>>> 
+0

向下投票評論會很好 - 我還會學習怎樣? – wwii

2

還有一個不同的方式來做到:

listy = ['item1', 'item2','item3','item4','item5', 'item6'] 

第一種方式

print(', '.join('and, ' + listy[item] if item == len(listy)-1 else listy[item] 
for item in xrange(len(listy)))) 

output >>> item1, item2, item3, item4, item5, and, item6 

第二種方式

print(', '.join(item for item in listy[:-1]), 'and', listy[-1]) 

output >>> (item1, item2, item3, item4, item5, 'and', 'item6') 
0

您也可以嘗試在quoter

>>> import quoter 
>>> mylist = ['a', 'b', 'c'] 
>>> quoter.and_join(mylist) 
'a, b, and c' 
>>> quoter.or_join(mylist) 
'a, b, or c' 

https://pypi.python.org/pypi/quoter

相關問題