【问题标题】:Find common character in list of strings在字符串列表中查找常见字符
【发布时间】:2022-01-25 13:22:01
【问题描述】:

我想在不使用集合库的情况下在给定的字符串列表中查找常用字符。有人可以帮忙吗?

输入:

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

输出:

result - ap

【问题讨论】:

  • ["abc", "bca"] 的结果是什么?
  • 我们不是您的个人代码编写服务。向我们展示您到目前为止所写的内容以及您具体遇到的问题。 How to Ask

标签: python python-3.x


【解决方案1】:

您的示例可能有 3 种解释:任何位置的 common char、相同位置的 common char 或开头的 common chars(所有这些都会导致 'ap'):

要在任何位置获取常用字符,您可以在所有字符串上使用集合交集:

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

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

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

获取相同位置的常用字符:

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

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

print(common) # ap

要获得最长的公共前缀(没有库):

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

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

print(strings[0][:common]) # ap

【讨论】:

    【解决方案2】:

    像这样:

    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
    

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

    【讨论】:

      【解决方案3】:
      print({c for c in strings[0] if all(c in s for s in strings[1:])})
      

      【讨论】:

        猜你喜欢
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        • 2019-04-25
        • 1970-01-01
        • 2012-12-08
        • 2017-04-25
        • 1970-01-01
        • 2020-03-20
        相关资源
        最近更新 更多