代码之家  ›  专栏  ›  技术社区  ›  Mittenchops

用于python中查找替换列表的itertools或functools

  •  4
  • Mittenchops  · 技术社区  · 13 年前

    我有一组有时无效的字符串,我想用特定的更好的字符串替换它们。我一直在玩functools和itertools,并想尝试将它们应用于这个问题,但我有点卡住了。以下是我所拥有的:

    s1 = 'how to sing songs'
    s2 = 'This is junk'
    s3 = "This is gold"
    s4 = 'HTML'
    s5 = 'html'
    s6 = 'i'
    mylist = [s1,s2,s3,s4,s5,s6]
    
    replacements = [('html','HTML'),('how to sing songs','singing'),('This is junk', ''),('i','')]
    

    我想要一个函数算法,它可以说,对于mylist中的每个字符串,对于replacements中的每个替换,string.replacement(replacement[0],replacement[1])。

    我想到的是。。。

    map(lambda x,y: x.replace(y[0],y[1]),mylist,replacements)
    map(partial(lambda x,y: x.replace(y[0],y[1]),mylist),replacements)
    

    但第一个需要额外的参数,第二个列表对象没有属性替换。有没有一种巧妙的功能性方法来解决这个问题?

    2 回复  |  直到 13 年前
        1
  •  4
  •   Andrew Clark    13 年前
    >>> [reduce(lambda x, y: x.replace(y[0], y[1]), replacements, s) for s in mylist]
    ['singing', '', 'This is gold', 'HTML', 'HTML']
    

    具有的等效代码 map() 而不是列表理解:

    map(partial(reduce, lambda x, y: x.replace(y[0], y[1]), replacements), mylist)
    
        2
  •  -1
  •   DaveTheScientist    13 年前

    听起来你想要的东西真的很快。在这种情况下,您应该真正使用字典,因为查找速度非常快。

    一个工作示例:

    mylist = ['how to sing songs', 'This is junk', "This is gold", 'HTML', 'html', 'i']
    replacements = {'html':'HTML', 'how to sing songs':'singing', 'This is junk':'', 'i':''}
    
    print [replacements.get(word, word) for word in mylist]  
    # ['singing', '', 'This is gold', 'HTML', 'HTML', ''] 
    
    推荐文章