python算法:Which are in?

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
#Example 1: a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns ["arp", "live", "strong"]

#Example 2: a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns []


我的解法:

def in_array(array1, array2):
    l=[]
    for i in array1:
        for j in array2:
            if i in j:   # and not i in l:
                l.append(i)
                break  #注意什么时候可以不写
    l=list(set(l))#set[]会变成{},sort只用于[],所以还要在list()一样 #sorted()就可以作用于{}!!
    l.sort()#排序
    return l

  #set一个[]后变会{},所以l=list(set([]))但是但是但是!

  也可以这样写:

l=sorted(set(l)) sorted又让{}变[]

大神解法:

def in_array(a1, a2):
    return sorted({sub for sub in a1 if any(sub in s for s in a2)})

又是牛逼的单行!!

还有any()的用法

{}换成[]就还是有重复出现,{}是不重复的一种格式!!!!




猜你喜欢

转载自blog.csdn.net/qulengdai0563/article/details/80185078