如何过滤掉至少有一个唯一字母的单词
我有一长串名为words. 所有字符串都具有相同的长度,即 5。对于 {0,...,4} 中的任何 i,我们可以检查i字符串的第 'th 个字母是否也是该字符串中任何其他字符串的第 i 个字母列表。i如果不是,我们称在'th 位置的字母是唯一的。
我想从我的名单对其存在任何删除所有字符串i为其i“个字母是独一无二的。
作为一个非常简单的例子,考虑:words = ["apple", "amber", "bpple", "bmber", "appld"]. 应该删除字符串“appld”,因为d它在第 4 位是唯一的。
有没有一种巧妙的方法来做到这一点?
回答
使用collections.Counter和zip(*...)换位成语:
from collections import Counter
# counts for every index
bypos = [*map(Counter, zip(*words))]
# disallow count 1 for any letter x in its respective position
words = [w for w in words if all(c[x]!=1 for x, c in zip(w, bypos))]
# ['apple', 'amber', 'bpple', 'bmber']
请注意,在单次迭代中重建列表比重复删除元素更好。
关于此处使用的实用程序的一些文档:
collections.Countermapzipall- 开箱操作员
*