2016-11-09 52 views
3

假设我们有5个字符串列表:查看五个字符串中的任何一个是否相同的最有效方法是什么?

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

我希望看到任何字符串是否相同(奖金:如果有任何字符串相同拿到该列表中的相同元素的索引) 。

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

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

回答

3

一组哈希并找到长度

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

一个好的方法来得到,如果它们存在的想法同时得到指标是创建在保存此信息一点点功能返回值。

具体来说,它使用一个集合检查成员资格,如果找到相似的索引,返回这些列表(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] 
相关问题