加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:15:27 所属栏目: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中,则应该大声说出来.
>速度并不重要,但代码的优雅是.所以代码越好读越好 – 我知道的那种主观.
>输出顺序并不重要,因为我可以只转换为字符串并排序()它.

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

解决方法

您可以使用collections.Counter对象,可以相互减去:
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']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读