Find *most* common prefix of strings - a better way?
问题 I have a list of keys ['foo_a','foo_b','foo_c','fnord'] All of the similar solutions here assume that you have no fnord 's in your text. I have this code that does the job: def detect_prefix(keys): PCT = 0.70 # cutof pre = '' l = len(keys) for i in range(0, len(max(keys, key=len))): keys = filter(lambda k: k.startswith(pre), keys) cnt = dict() for k in map(lambda k: k[i], keys): cnt.setdefault(k,0) cnt[k] +=1 if cnt[max(cnt)] / float(l) >= PCT: pre += max(cnt) else: break return pre I have a