您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 删除字符串中的常用字母

5b51 2022/1/14 8:22:37 python 字数 2859 阅读 562 来源 www.jb51.cc/python

所以我有一个有趣的问题. 我试着写一些字混乱,我需要知道我用过哪些字母,哪些字母没用.到目前为止,我有以下代码: def remove_common(x,y): sort = sort = lambda x: "".join(c for c in sorted(x.lower()) if c.isalpha()) x,y = sort(x), sort(y) //some co

概述

我试着写一些字混乱,我需要知道我用过哪些字母,哪些字母没用.到目前为止,我有以下代码

def remove_common(x,y):
   sort = sort = lambda x: "".join(c for c in sorted(x.lower()) if c.isalpha())
   x,y  = sort(x),sort(y)
   //some code that removes y from x
   return leftovers

print remove_common("Lets chat about code","that cool cat")
print remove_common("A silly word","a lil sword")
print remove_common("The Thing","Height")

>>> "bdeesu"
>>> "iy"
>>> "tn"

我正在寻找一种简单的方法删除两者中的字母,但在必要时留下重复的内容.

>字符串转换为小写,非字母被删除
>重复重要,所以如果x =“aa”且y =“a”,则结果为“a”,而不是“”.我认为这排除了套装的使用.
>如果y中的字母不在x中,则应该大声说出来.
>速度并不重要,但代码的优雅是.所以代码越好读越好 – 我知道的那种主观.
>输出顺序并不重要,因为我可以只转换为字符串并排序()它.

我已经查看了其他答案,但这些答案主要与仅给出不出现在一个字母中的字母有关并删除重复.

import collections

def remove_common(x,y):
    count = lambda x: collections.Counter(c for c in x.lower() if c.isalpha())
    cx,cy = count(x),count(y)
    diff  = cx - cy
    rev_diff = cy - cx
    assert len(rev_diff) == 0,"%s in y and not x" % "".join(rev_diff.elements())

    return "".join(sorted(diff.elements()))

作为正在发生的事情的演示:

>>> c1 = collections.Counter("hello world")
>>> c2 = collections.Counter("hey worlds")
>>> c1 - c2
Counter({'l': 2,'o': 1})
>> (c1 - c2).elements()
['l','l','o']

总结

以上是编程之家为你收集整理的python – 删除字符串中的常用字母全部内容,希望文章能够帮你解决python – 删除字符串中的常用字母所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶