2014-11-25 126 views
0

我是python新手。我试图创建一个函数,它将字符串和列表作为参数,并为字符串中找到的每个列表元素(这应该作为元组返回)返回一个布尔值。我曾尝试下面的代码列表元组返回python

def my_check(str1, list1): 
    words = str1.split() 
    x = 1 
    for l in range(len(list1)): 
     for i in range(len(words)): 
      if list1[l] == words[i]: 
       x = x+1 
     if (x > 1): 
      print(True) 
      x = 1 
     else: 
      print(False) 

output = my_check('my name is ide3', ['is', 'my', 'no']) 
print(output) 

此代码输出

True 
True 
False 

我怎样才能返回这个值作为一个元组

>>> output 
(True, True, False) 

任何想法表示赞赏。

回答

0

发电机救援(编辑:得到了它向后第一次)

def my_check(str1, list1): 
    return tuple(w in str1.split() for w in list1) 
1

如果要修改,打印的东西到返回的东西代码的任何代码,您必须:

  1. 在顶部创建一个空集合。
  2. 将每个print调用替换为将值添加到集合的调用。
  3. 返回集合。

所以:

def my_check(str1, list1): 
    result =() # create an empty collection 
    words = str1.split() 
    x = 1 
    for l in range(len(list1)): 
     for i in range(len(words)): 
      if list1[l] == words[i]: 
       x = x+1 
     if (x > 1): 
      result += (True,) # add the value instead of printing 
      x = 1 
     else: 
      result += (False,) # add the value instead of printing 
    return result # return the collection 

这是一个有点尴尬与元组,但它的作品。你可能会想要考虑使用一个列表,因为这样做不那么尴尬(如果你真的需要转换它,最后总是可以使用return tuple(result))。

0

考虑到效率,也许我们应该建立从str1.split一组()首先是因为在一组查询项比快得多列表中,这样的:

def my_check(str1, list1): 
    #build a set from the list str1.split() first 
    wordsSet=set(str1.split()) 
    #build a tuple from the boolean generator 
    return tuple((word in wordsSet) for word in list1) 
0

您可以检查直接在字符串中的字符串,所以split()不是必需的。因此,这也工作:

def my_check(str1, list1): 
    return tuple(w in mystr for w in mylist) 
    # return [w in mystr for w in mylist] # Much faster than creating tuples 

然而,由于返回而不是一个新的列表是不是经常需要一个元组,你应该能够只使用直列表理解上述(您总是可以在列表转换为如果你不得不在你的代码中下游)。

蟒蛇结果:

In [117]: %timeit my_check_wtuple('my name is ide3', ['is', 'my', 'no']) 
100000 loops, best of 3: 2.31 µs per loop 

In [119]: %timeit my_check_wlist('my name is ide3', ['is', 'my', 'no']) 
1000000 loops, best of 3: 614 ns per loop