【问题标题】:What is the most efficient way of seeing whether any of five strings are identical?查看五个字符串中的任何一个是否相同的最有效方法是什么?
【发布时间】:2017-03-23 09:54:23
【问题描述】:

假设我们有一个包含 5 个字符串的列表:

list = ['hello', 'alloha', 'hi there', 'good day', 'hello']

我想查看是否有任何字符串相同(奖励:如果任何字符串相同,则获取列表中相同元素的索引)。

解决这个小任务最有效的方法是什么?它适用于包含两个以上相同元素的更大列表吗?

我在想也许(不知何故)比较每个字符串的长度,然后如果长度数学比较相同位置的字母。

【问题讨论】:

    标签: python string python-3.x string-comparison


    【解决方案1】:

    用一组散列它们并比较长度

    if len(set(mylist)) != len(mylist):
        print("some members match!")
    else:
        print("no members match")
    

    【讨论】:

      【解决方案2】:

      了解它们是否存在同时获取索引的一个好方法是创建一个小函数,将这些信息保存在返回值中。

      具体来说,它使用集合检查成员资格,如果找到类似的索引,则返回这些列表(ergo,类似的词存在),如果没有找到,则返回一个空列表(意思是,没有匹配项):

      def sim(ls):
          s = set()
          for i, j in enumerate(ls):
              if j not in s:
                  s.add(j)  # add the value
              else:
                  yield i   # yield the index
      

      然后,如果需要,您可以获取此函数产生的结果并检查 if 条件中的值:

      lst = ['hello', 'alloha', 'hi there', 'good day', 'hello']
      res = list(sim(lst))   # get indices if they exist
      
      # check against them
      if res:
          print("Similar values in indices :", res)
      else:
          print("print("No similar words")
      

      打印出来:

      Similar values in indices : [4]
      

      【讨论】:

        猜你喜欢
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        • 2011-12-07
        相关资源
        最近更新 更多