2014-11-02 71 views
3

什麼是加入句子部分列表以便結果爲「a,b和c」的優雅方法,其中list[ 'a', 'b', 'c' ]?僅指定', '.join()只能達到「a,b,c」。Python string.join(list)last and entry with「and」

(另外,我也做了一些搜索這個,但顯然我不是寫的短語,因爲我還沒有拿出任何東西,除了列舉的清單嘍。)

回答

4
L = ['a','b','c'] 

if len(L)>2: 
    print ', '.join(L[:-1]) + ", and " + str(L[-1]) 
elif len(L)==2: 
    print ' and '.join(L) 
elif len(L)==1: 
    print L[0] 

Works的長度爲0,1,2,和3+。

我包括長度2的原因是爲了避免逗號:a and b

如果列表長度爲1,那麼它只輸出a

如果列表爲空,則不輸出任何內容。

1

假設len(words)>2,你可以加入使用', '第一n-1詞語,並使用標準字符串格式化添加的最後一個字:

def join_words(words): 
    if len(words) > 2: 
     return '%s, and %s' % (', '.join(words[:-1]), words[-1]) 
    else: 
     return ' and '.join(words) 
+1

即將發佈完全相同的答案 – Vlad 2014-11-02 21:48:51

+0

這裏假設你將始終有3分或更多的話 – sirlark 2014-11-02 21:49:13

+0

@sirlark,感謝指出了這一點。現在修好。 – shx2 2014-11-02 21:50:52

1
"{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0] 


In [25]: l =[ 'a'] 

In [26]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0] 
Out[26]: 'a' 

In [27]: l =[ 'a','b'] 

In [28]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0] 
Out[28]: 'a and b' 

In [29]: l =[ 'a','b','c'] 

In [30]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0] 
Out[30]: 'a,b and c' 
0
l = ['a','b','c'] 
if len(l) > 1: 
    print ",".join(k[:-1]) + " and " + k[-1] 
else:print l[0] 

exapmles:

l = ['a','b','c'] 
a,b and c 

l = ['a','b'] 
a and b 

l=['a'] 
a