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" 我正在寻找一种简单的方法来删除两者中的字母,但在必要时留下重复的内容. >字符串转换为小写,非字母被删除 我已经查看了其他答案,但这些答案主要与仅给出不出现在一个字母中的字母有关并删除重复. 解决方法
您可以使用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'] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |