查看五个字符串是否相同的最有效方法是什么?

What is the most efficient way of seeing whether any of five strings are identical?

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

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

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

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

我在想也许(以某种方式)比较每个字符串的长度,然后如果长度数学比较相同位置的字母。

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

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

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

具体来说,它使用一个集合检查成员资格,如果找到相似的索引 return 则列出这些索引(因此,存在相似的词),而如果找到 none,returns 一个空列表(意思是,没有匹配项):

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]