2014-10-10 77 views
-1

我有一個長長的清單,如:延長每一個字符串列表中的標點符號

['This', 'Hello', 'Good', ...] 

現在,我希望有一個新的列表,看起來像:

['This', 'This.','This,','This?','This!','This:','Hello','Hello.','Hello,','Hello?','Hello!','Hello:', 'Good', 'Good.', ...] 

所以我想添加標點符號每一個字。這甚至有可能嗎?

+0

是的,當然是。你發現了什麼 – 2014-10-10 08:35:53

+0

現在我看到了你的答案,你不想知道。 :-D – 2014-10-10 08:47:00

+0

你讓我好奇:P – 2014-10-10 08:47:57

回答

1

這將是最簡單的方法:

newlist =[] 
for item in oldlist: 
    newlist.append(item) 
    newlist.append(item+'.') 
    newlist.append(item+',') 
    newlist.append(item+'?') 
    newlist.append(item+'!') 
    newlist.append(item+':') 

短一點:

newlist =[] 
adds = ['', ',', '.', '?', '!', ':'] 
for item in oldlist: 
    for add in adds: 
     newlist.append(item+add) 

OR爲列表理解:

adds = ['', ',', '.', '?', '!', ':'] 
newlist = [item+add for item in oldlist for add in adds] 

作爲一個班輪:

newlist = [item+add for item in oldlist for add in ['', ',', '.', '?', '!', ':']] 
+0

太好了,謝謝!我將與列表理解一起工作,效果很好。 – 2014-10-10 08:46:24

1

一些功能愛

from itertools import product 

l1 = ['This', 'Hello', 'Good'] 
l2 = ['', '.', ',', '?', '!', ':'] 

newlist = ["".join(e) for e in product(l1, l2)] 

print newlist 
相關問題