python-3.x 在字符串列表中查找常用字符

64jmpszr  于 2022-12-05  发布在  Python
关注(0)|答案(3)|浏览(126)

我想在不使用集合库的情况下找到给定字符串列表中的常用字符。有人能帮我吗?
输入:

strings = ["apple", "app", "ape"]

输出量:

result - ap
bt1cpqcv

bt1cpqcv1#

You example could have 3 interpretations: common char at any position, common chars at same position, or common chars at the beginning (all these would result in 'ap'):
To get common characters at any position, you can use a set intersection over all strings:

strings = ["apple", "app", "ape"]

common = set.intersection(*map(set,strings))

print(common) # {'p', 'a'}

To get common characters at the same positions:

strings = ["apple", "app", "ape"]

common = "".join(p for p,*r in zip(*strings) if all(p==c for c in r))

print(common) # ap

To get the longest common prefix (without libraries):

strings = ["apple", "app", "ape"]

common = next((strings[0][:i] for i,(p,*r) in enumerate(zip(*strings)) 
                              if any(p!=c for c in r)),strings[0])

print(common) # ap
q9yhzks0

q9yhzks02#

就像这样:

strings = ["apple", "app", "ape"]

char_sets = [{*s} for s in strings]

result_set = char_sets[0]
for char_set in char_sets[1:]:
    result_set.intersection_update(char_set)

print(''.join(sorted(list(result_set))))

退货:

ap

假设您需要对所有常用字符进行排序。

t9eec4r0

t9eec4r03#

print({c for c in strings[0] if all(c in s for s in strings[1:])})

相关问题