能否使用列表推导式完成此示例:
a = ['test', 'smth']
b = ['test Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
'test Nulla lectus ligula',
'imperdiet at porttitor quis',
'smth commodo eget tortor',
'Orci varius natoque penatibus et magnis dis parturient montes']
for s in a:
b = [el.replace(s,'') for el in b]
我希望能从一系列句子中删除特定单词。我可以使用循环来实现,但我认为可能有一行代码的解决方案。
我尝试了以下代码:
b = [[el.replace(s,'') for el in b] for s in a ]
但它出了问题。
我得到了很多高质量的答案,但现在我有一个更复杂的问题:如果我想使用词语组合怎么办?
a = ['test', 'smth commodo']
非常感谢您提供了这么多的答案!我对所有解决方案进行了速度测试,以下是结果: 我对100次计算取平均值(最后一个除外,因为等待时间太长)。
b=10 a=2 | b=9000 a=2 | b=9000 a=100 | b=45k a=500
---------------------------------+-------------+--------------+---------------
COLDSPEED solution: 0.0000206 | 0.0311071 | 0.0943433 | 4.5012770
Jean Fabre solution: 0.0000871 | 0.1722340 | 0.2635452 | 5.2981001
Jpp solution: 0.0000212 | 0.0474531 | 0.0464369 | 0.2450547
Ajax solution: 0.0000334 | 0.0303891 | 0.5262040 | 11.6994496
Daniel solution: 0.0000167 | 0.0162156 | 0.1301132 | 6.9071504
Kasramvd solution: 0.0000120 | 0.0084146 | 0.1704623 | 7.5648351
我们可以看到Jpp解决方案是最快的,但我们不能使用它 - 它是所有其他解决方案中唯一不能在单词组合上工作的解决方案(我已经写信给他,希望他会改进他的答案!)。因此,看起来@cᴏʟᴅsᴘᴇᴇᴅ的解决方案是大数据集上最快的。