我有一个长长的清单,如:延长每一个字符串列表中的标点符号
['This', 'Hello', 'Good', ...]
现在,我希望有一个新的列表,看起来像:
['This', 'This.','This,','This?','This!','This:','Hello','Hello.','Hello,','Hello?','Hello!','Hello:', 'Good', 'Good.', ...]
所以我想添加标点符号每一个字。这甚至有可能吗?
我有一个长长的清单,如:延长每一个字符串列表中的标点符号
['This', 'Hello', 'Good', ...]
现在,我希望有一个新的列表,看起来像:
['This', 'This.','This,','This?','This!','This:','Hello','Hello.','Hello,','Hello?','Hello!','Hello:', 'Good', 'Good.', ...]
所以我想添加标点符号每一个字。这甚至有可能吗?
这将是最简单的方法:
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 ['', ',', '.', '?', '!', ':']]
太好了,谢谢!我将与列表理解一起工作,效果很好。 – 2014-10-10 08:46:24
一些功能爱
from itertools import product
l1 = ['This', 'Hello', 'Good']
l2 = ['', '.', ',', '?', '!', ':']
newlist = ["".join(e) for e in product(l1, l2)]
print newlist
是的,当然是。你发现了什么 – 2014-10-10 08:35:53
现在我看到了你的答案,你不想知道。 :-D – 2014-10-10 08:47:00
你让我好奇:P – 2014-10-10 08:47:57