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

3
假设我们有一个包含5个字符串的列表:
list = ['hello', 'alloha', 'hi there', 'good day', 'hello']

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

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

我考虑过(某种方式)将每个字符串的长度相互比较,然后如果长度匹配,则比较相同位置上的字母。

2个回答

4

使用集合哈希它们并比较长度

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

1
一个好的方法来判断它们是否存在,同时获取索引,是创建一个小函数,将这些信息保存在返回值中。具体来说,它使用一个集合来检查成员资格,如果找到类似的索引,则返回这些索引的列表(因此,存在类似的单词),而如果没有找到,则返回一个空列表(表示没有匹配项):
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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接